blob: c1cfd36fd1374ec986c8e6babb670f898ce7f2de [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregor9e876872011-03-01 18:12:44 +000015#include "TypeLocBuilder.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Faisal Valifad9e132013-09-26 19:54:12 +000018#include "clang/AST/ASTLambda.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000021#include "clang/AST/CommentDiagnostic.h"
John McCall384aff82010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Chandler Carrutha7689ef2011-03-27 09:46:56 +000025#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000026#include "clang/AST/ExprCXX.h"
Sebastian Redld3a413d2009-04-26 20:35:05 +000027#include "clang/AST/StmtCXX.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Basic/SourceManager.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
32#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
33#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
34#include "clang/Parse/ParseDiagnostic.h"
35#include "clang/Sema/CXXFieldCollector.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/DelayedDiagnostic.h"
38#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/ParsedTemplate.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/ScopeInfo.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000043#include "llvm/ADT/SmallString.h"
John McCall66755862009-12-24 09:58:38 +000044#include "llvm/ADT/Triple.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000045#include <algorithm>
Douglas Gregor9a8c9a22009-09-28 21:14:19 +000046#include <cstring>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000047#include <functional>
Reid Spencer5f016e22007-07-11 17:01:13 +000048using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000049using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000050
Richard Smithc89edf52011-07-01 19:46:12 +000051Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
52 if (OwnedType) {
53 Decl *Group[2] = { OwnedType, Ptr };
54 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
55 }
56
John McCalld226f652010-08-21 09:40:31 +000057 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner682bf922009-03-29 16:50:03 +000058}
59
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000060namespace {
61
62class TypeNameValidatorCCC : public CorrectionCandidateCallback {
63 public:
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000064 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
65 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000066 WantExpressionKeywords = false;
67 WantCXXNamedCasts = false;
68 WantRemainingKeywords = false;
69 }
70
71 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
72 if (NamedDecl *ND = candidate.getCorrectionDecl())
73 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
74 (AllowInvalidDecl || !ND->isInvalidDecl());
75 else
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000076 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000077 }
78
79 private:
80 bool AllowInvalidDecl;
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000081 bool WantClassName;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000082};
83
84}
85
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +000086/// \brief Determine whether the token kind starts a simple-type-specifier.
87bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
88 switch (Kind) {
89 // FIXME: Take into account the current language when deciding whether a
90 // token kind is a valid type specifier
91 case tok::kw_short:
92 case tok::kw_long:
93 case tok::kw___int64:
94 case tok::kw___int128:
95 case tok::kw_signed:
96 case tok::kw_unsigned:
97 case tok::kw_void:
98 case tok::kw_char:
99 case tok::kw_int:
100 case tok::kw_half:
101 case tok::kw_float:
102 case tok::kw_double:
103 case tok::kw_wchar_t:
104 case tok::kw_bool:
105 case tok::kw___underlying_type:
106 return true;
107
108 case tok::annot_typename:
109 case tok::kw_char16_t:
110 case tok::kw_char32_t:
111 case tok::kw_typeof:
David Majnemerff989a82013-09-22 01:24:26 +0000112 case tok::annot_decltype:
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +0000113 case tok::kw_decltype:
114 return getLangOpts().CPlusPlus;
115
116 default:
117 break;
118 }
119
120 return false;
121}
122
Douglas Gregord6efafa2009-02-04 19:16:12 +0000123/// \brief If the identifier refers to a type name within this scope,
124/// return the declaration of that type.
125///
126/// This routine performs ordinary name lookup of the identifier II
127/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000128/// determine whether the name refers to a type. If so, returns an
129/// opaque pointer (actually a QualType) corresponding to that
130/// type. Otherwise, returns NULL.
Dmitri Gribenko8eead162013-05-03 13:12:11 +0000131ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallb3d87482010-08-24 05:47:05 +0000132 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000133 bool isClassName, bool HasTrailingDot,
Douglas Gregor9e876872011-03-01 18:12:44 +0000134 ParsedType ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000135 bool IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000136 bool WantNontrivialTypeSourceInfo,
137 IdentifierInfo **CorrectedII) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000138 // Determine where we will perform name lookup.
139 DeclContext *LookupCtx = 0;
140 if (ObjectTypePtr) {
John McCallb3d87482010-08-24 05:47:05 +0000141 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000142 if (ObjectType->isRecordType())
143 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskinedc28772010-04-07 23:29:58 +0000144 } else if (SS && SS->isNotEmpty()) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000145 LookupCtx = computeDeclContext(*SS, false);
146
147 if (!LookupCtx) {
148 if (isDependentScopeSpecifier(*SS)) {
149 // C++ [temp.res]p3:
150 // A qualified-id that refers to a type and in which the
151 // nested-name-specifier depends on a template-parameter (14.6.2)
152 // shall be prefixed by the keyword typename to indicate that the
153 // qualified-id denotes a type, forming an
154 // elaborated-type-specifier (7.1.5.3).
155 //
156 // We therefore do not perform any name lookup if the result would
157 // refer to a member of an unknown specialization.
Richard Smithc5a89a12012-04-02 01:30:27 +0000158 if (!isClassName && !IsCtorOrDtorName)
John McCallb3d87482010-08-24 05:47:05 +0000159 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000160
John McCall33500952010-06-11 00:33:02 +0000161 // We know from the grammar that this name refers to a type,
162 // so build a dependent node to describe the type.
Douglas Gregor9e876872011-03-01 18:12:44 +0000163 if (WantNontrivialTypeSourceInfo)
164 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
165
166 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallb3d87482010-08-24 05:47:05 +0000167 QualType T =
Douglas Gregor9e876872011-03-01 18:12:44 +0000168 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +0000169 II, NameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +0000170
171 return ParsedType::make(T);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000172 }
173
John McCallb3d87482010-08-24 05:47:05 +0000174 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000175 }
176
John McCall77bb1aa2010-05-01 00:40:08 +0000177 if (!LookupCtx->isDependentContext() &&
178 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallb3d87482010-08-24 05:47:05 +0000179 return ParsedType();
Douglas Gregor42c39f32009-08-26 18:27:52 +0000180 }
Eli Friedman0f0615b2009-12-21 01:42:38 +0000181
182 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
183 // lookup for class-names.
184 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
185 LookupOrdinaryName;
186 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000187 if (LookupCtx) {
188 // Perform "qualified" name lookup into the declaration context we
189 // computed, which is either the type of the base of a member access
190 // expression or the declaration context associated with a prior
191 // nested-name-specifier.
192 LookupQualifiedName(Result, LookupCtx);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000193
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000194 if (ObjectTypePtr && Result.empty()) {
195 // C++ [basic.lookup.classref]p3:
196 // If the unqualified-id is ~type-name, the type-name is looked up
197 // in the context of the entire postfix-expression. If the type T of
198 // the object expression is of a class type C, the type-name is also
199 // looked up in the scope of class C. At least one of the lookups shall
200 // find a name that refers to (possibly cv-qualified) T.
201 LookupName(Result, S);
202 }
203 } else {
204 // Perform unqualified name lookup.
205 LookupName(Result, S);
206 }
207
Chris Lattner22bd9052009-02-16 22:07:16 +0000208 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000209 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +0000210 case LookupResult::NotFound:
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000211 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000212 if (CorrectedII) {
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +0000213 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000214 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000215 Kind, S, SS, Validator);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000216 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
217 TemplateTy Template;
218 bool MemberOfUnknownSpecialization;
219 UnqualifiedId TemplateName;
220 TemplateName.setIdentifier(NewII, NameLoc);
221 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
222 CXXScopeSpec NewSS, *NewSSPtr = SS;
223 if (SS && NNS) {
224 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
225 NewSSPtr = &NewSS;
226 }
227 if (Correction && (NNS || NewII != &II) &&
228 // Ignore a correction to a template type as the to-be-corrected
229 // identifier is not a template (typo correction for template names
230 // is handled elsewhere).
David Blaikie4e4d0842012-03-11 07:00:24 +0000231 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000232 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
233 false, Template, MemberOfUnknownSpecialization))) {
234 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
235 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000236 IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000237 WantNontrivialTypeSourceInfo);
238 if (Ty) {
Richard Smith2d670972013-08-17 00:46:16 +0000239 diagnoseTypo(Correction,
240 PDiag(diag::err_unknown_type_or_class_name_suggest)
241 << Result.getLookupName() << isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000242 if (SS && NNS)
243 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
244 *CorrectedII = NewII;
245 return Ty;
246 }
247 }
248 }
249 // If typo correction failed or was not performed, fall through
Chris Lattner22bd9052009-02-16 22:07:16 +0000250 case LookupResult::FoundOverloaded:
John McCall7ba107a2009-11-18 02:36:19 +0000251 case LookupResult::FoundUnresolvedValue:
John McCallc373d482010-01-27 01:50:18 +0000252 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000253 return ParsedType();
Douglas Gregorb696ea32009-02-04 17:00:24 +0000254
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000255 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000256 // Recover from type-hiding ambiguities by hiding the type. We'll
257 // do the lookup again when looking for an object, and we can
258 // diagnose the error then. If we don't do this, then the error
259 // about hiding the type will be immediately followed by an error
260 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000261 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
262 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000263 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000264 }
John McCall6e247262009-10-10 05:48:19 +0000265
Douglas Gregor31a19b62009-04-01 21:51:26 +0000266 // Look to see if we have a type anywhere in the list of results.
267 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
268 Res != ResEnd; ++Res) {
269 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000270 if (!IIDecl ||
271 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000272 IIDecl->getLocation().getRawEncoding())
273 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000274 }
275 }
276
277 if (!IIDecl) {
278 // None of the entities we found is a type, so there is no way
279 // to even assume that the result is a type. In this case, don't
280 // complain about the ambiguity. The parser will either try to
281 // perform this lookup again (e.g., as an object name), which
282 // will produce the ambiguity, or will complain that it expected
283 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000284 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000285 return ParsedType();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000286 }
287
288 // We found a type within the ambiguous lookup; diagnose the
289 // ambiguity and then return that type. This might be the right
290 // answer, or it might not be, but it suppresses any attempt to
291 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000292 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000293
Chris Lattner22bd9052009-02-16 22:07:16 +0000294 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000295 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000296 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000297 }
298
Chris Lattner10ca3372009-10-25 17:16:46 +0000299 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000300
Chris Lattner10ca3372009-10-25 17:16:46 +0000301 QualType T;
302 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000303 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000304
Chris Lattner10ca3372009-10-25 17:16:46 +0000305 if (T.isNull())
306 T = Context.getTypeDeclType(TD);
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000307
308 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
309 // constructor or destructor name (in such a case, the scope specifier
310 // will be attached to the enclosing Expr or Decl node).
311 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor9e876872011-03-01 18:12:44 +0000312 if (WantNontrivialTypeSourceInfo) {
313 // Construct a type with type-source information.
314 TypeLocBuilder Builder;
315 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
316
317 T = getElaboratedType(ETK_None, *SS, T);
318 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara38a42912012-02-06 19:09:27 +0000319 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor9e876872011-03-01 18:12:44 +0000320 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
321 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
322 } else {
323 T = getElaboratedType(ETK_None, *SS, T);
324 }
325 }
Chris Lattner10ca3372009-10-25 17:16:46 +0000326 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian02b0d652011-03-08 19:12:46 +0000327 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000328 if (!HasTrailingDot)
329 T = Context.getObjCInterfaceType(IDecl);
330 }
331
332 if (T.isNull()) {
John McCalla24dc2e2009-11-17 02:14:36 +0000333 // If it's not plausibly a type, suppress diagnostics.
334 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000335 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000336 }
John McCallb3d87482010-08-24 05:47:05 +0000337 return ParsedType::make(T);
Reid Spencer5f016e22007-07-11 17:01:13 +0000338}
339
Chris Lattner4c97d762009-04-12 21:49:30 +0000340/// isTagName() - This method is called *for error recovery purposes only*
341/// to determine if the specified name is a valid tag name ("struct foo"). If
342/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matos6666ed42012-08-31 18:45:21 +0000343/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
344/// cases in C where the user forgot to specify the tag.
Chris Lattner4c97d762009-04-12 21:49:30 +0000345DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
346 // Do a tag name lookup in this scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000347 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
348 LookupName(R, S, false);
349 R.suppressDiagnostics();
350 if (R.getResultKind() == LookupResult::Found)
John McCall1bcee0a2009-12-02 08:25:40 +0000351 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattner4c97d762009-04-12 21:49:30 +0000352 switch (TD->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000353 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matos6666ed42012-08-31 18:45:21 +0000354 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000355 case TTK_Union: return DeclSpec::TST_union;
356 case TTK_Class: return DeclSpec::TST_class;
357 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattner4c97d762009-04-12 21:49:30 +0000358 }
359 }
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Chris Lattner4c97d762009-04-12 21:49:30 +0000361 return DeclSpec::TST_unspecified;
362}
363
Francois Pichet6943e9b2011-04-13 02:38:49 +0000364/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
365/// if a CXXScopeSpec's type is equal to the type of one of the base classes
366/// then downgrade the missing typename error to a warning.
367/// This is needed for MSVC compatibility; Example:
368/// @code
369/// template<class T> class A {
370/// public:
371/// typedef int TYPE;
372/// };
373/// template<class T> class B : public A<T> {
374/// public:
375/// A<T>::TYPE a; // no typename required because A<T> is a base class.
376/// };
377/// @endcode
Francois Pichetf11dbe92011-10-11 01:50:09 +0000378bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000379 if (CurContext->isRecord()) {
Francois Pichet3441a522011-04-13 02:44:57 +0000380 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000381
382 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
383 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
384 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
385 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
386 return true;
Francois Pichetf11dbe92011-10-11 01:50:09 +0000387 return S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000388 }
Francois Pichetf11dbe92011-10-11 01:50:09 +0000389 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000390}
391
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000392bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregora786fdb2009-10-13 23:27:22 +0000393 SourceLocation IILoc,
394 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000395 CXXScopeSpec *SS,
John McCallb3d87482010-08-24 05:47:05 +0000396 ParsedType &SuggestedType) {
Douglas Gregora786fdb2009-10-13 23:27:22 +0000397 // We don't have anything to suggest (yet).
John McCallb3d87482010-08-24 05:47:05 +0000398 SuggestedType = ParsedType();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000399
Douglas Gregor546be3c2009-12-30 17:04:44 +0000400 // There may have been a typo in the name of the type. Look up typo
401 // results, in case we have something that we can suggest.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000402 TypeNameValidatorCCC Validator(false);
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000403 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000404 LookupOrdinaryName, S, SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000405 Validator)) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000406 if (Corrected.isKeyword()) {
407 // We corrected to a keyword.
Richard Smith2d670972013-08-17 00:46:16 +0000408 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
409 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000410 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000411 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000412 if (!SS || !SS->isSet()) {
Richard Smith2d670972013-08-17 00:46:16 +0000413 diagnoseTypo(Corrected,
414 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000415 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +0000416 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
417 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000418 II->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000419 diagnoseTypo(Corrected,
420 PDiag(diag::err_unknown_nested_typename_suggest)
421 << II << DC << DroppedSpecifier << SS->getRange());
422 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000423 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000424 }
Douglas Gregor546be3c2009-12-30 17:04:44 +0000425
Kaelyn Uhraina934c312013-09-26 21:13:05 +0000426 CXXScopeSpec tmpSS;
427 if (Corrected.getCorrectionSpecifier())
428 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
429 SourceRange(IILoc));
Richard Smith2d670972013-08-17 00:46:16 +0000430 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhraina934c312013-09-26 21:13:05 +0000431 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
432 false, ParsedType(),
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000433 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000434 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor546be3c2009-12-30 17:04:44 +0000435 }
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000436 return true;
Douglas Gregor546be3c2009-12-30 17:04:44 +0000437 }
438
David Blaikie4e4d0842012-03-11 07:00:24 +0000439 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000440 // See if II is a class template that the user forgot to pass arguments to.
441 UnqualifiedId Name;
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000442 Name.setIdentifier(II, IILoc);
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000443 CXXScopeSpec EmptySS;
444 TemplateTy TemplateResult;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000445 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000446 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000447 Name, ParsedType(), true, TemplateResult,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000448 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov18062392013-08-27 13:15:56 +0000449 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000450 Diag(IILoc, diag::err_template_missing_args) << TplName;
451 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
452 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
453 << TplDecl->getTemplateParameters()->getSourceRange();
454 }
455 return true;
456 }
457 }
458
Douglas Gregora786fdb2009-10-13 23:27:22 +0000459 // FIXME: Should we move the logic that tries to recover from a missing tag
460 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
461
Douglas Gregor546be3c2009-12-30 17:04:44 +0000462 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000463 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregora786fdb2009-10-13 23:27:22 +0000464 else if (DeclContext *DC = computeDeclContext(*SS, false))
465 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000466 << II << DC << SS->getRange();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000467 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000468 unsigned DiagID = diag::err_typename_missing;
David Blaikie4e4d0842012-03-11 07:00:24 +0000469 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichetcf320c62011-04-22 08:25:24 +0000470 DiagID = diag::warn_typename_missing;
Francois Pichet6943e9b2011-04-13 02:38:49 +0000471
472 Diag(SS->getRange().getBegin(), DiagID)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000473 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
Douglas Gregora786fdb2009-10-13 23:27:22 +0000474 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregor849b2432010-03-31 17:46:05 +0000475 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000476 SuggestedType = ActOnTypenameType(S, SourceLocation(),
477 *SS, *II, IILoc).get();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000478 } else {
479 assert(SS && SS->isInvalid() &&
480 "Invalid scope specifier has already been diagnosed");
481 }
482
483 return true;
484}
Chris Lattner4c97d762009-04-12 21:49:30 +0000485
Douglas Gregor312eadb2011-04-24 05:37:28 +0000486/// \brief Determine whether the given result set contains either a type name
487/// or
488static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000489 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000490 NextToken.is(tok::less);
491
492 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
493 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
494 return true;
495
496 if (CheckTemplate && isa<TemplateDecl>(*I))
497 return true;
498 }
499
500 return false;
501}
502
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000503static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
504 Scope *S, CXXScopeSpec &SS,
505 IdentifierInfo *&Name,
506 SourceLocation NameLoc) {
Richard Smith69e48262012-09-06 01:37:56 +0000507 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
508 SemaRef.LookupParsedName(R, S, &SS);
509 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000510 const char *TagName = 0;
511 const char *FixItTagName = 0;
512 switch (Tag->getTagKind()) {
513 case TTK_Class:
514 TagName = "class";
515 FixItTagName = "class ";
516 break;
517
518 case TTK_Enum:
519 TagName = "enum";
520 FixItTagName = "enum ";
521 break;
522
523 case TTK_Struct:
524 TagName = "struct";
525 FixItTagName = "struct ";
526 break;
527
Joao Matos6666ed42012-08-31 18:45:21 +0000528 case TTK_Interface:
529 TagName = "__interface";
530 FixItTagName = "__interface ";
531 break;
532
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000533 case TTK_Union:
534 TagName = "union";
535 FixItTagName = "union ";
536 break;
537 }
538
539 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
540 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
541 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
542
Richard Smith69e48262012-09-06 01:37:56 +0000543 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
544 I != IEnd; ++I)
545 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
546 << Name << TagName;
547
548 // Replace lookup results with just the tag decl.
549 Result.clear(Sema::LookupTagName);
550 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000551 return true;
552 }
553
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000554 return false;
555}
556
Richard Smith05766812012-08-18 00:55:03 +0000557/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
558static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
559 QualType T, SourceLocation NameLoc) {
560 ASTContext &Context = S.Context;
561
562 TypeLocBuilder Builder;
563 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
564
565 T = S.getElaboratedType(ETK_None, SS, T);
566 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
567 ElabTL.setElaboratedKeywordLoc(SourceLocation());
568 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
569 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
570}
571
Douglas Gregor312eadb2011-04-24 05:37:28 +0000572Sema::NameClassification Sema::ClassifyName(Scope *S,
573 CXXScopeSpec &SS,
574 IdentifierInfo *&Name,
575 SourceLocation NameLoc,
Richard Smith05766812012-08-18 00:55:03 +0000576 const Token &NextToken,
577 bool IsAddressOfOperand,
578 CorrectionCandidateCallback *CCC) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000579 DeclarationNameInfo NameInfo(Name, NameLoc);
580 ObjCMethodDecl *CurMethod = getCurMethodDecl();
581
582 if (NextToken.is(tok::coloncolon)) {
583 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
584 QualType(), false, SS, 0, false);
585
586 }
587
588 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
589 LookupParsedName(Result, S, &SS, !CurMethod);
590
591 // Perform lookup for Objective-C instance variables (including automatically
592 // synthesized instance variables), if we're in an Objective-C method.
593 // FIXME: This lookup really, really needs to be folded in to the normal
594 // unqualified lookup mechanism.
595 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
596 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorec385cf2011-04-25 15:05:41 +0000597 if (E.get() || E.isInvalid())
Douglas Gregor312eadb2011-04-24 05:37:28 +0000598 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000599 }
600
601 bool SecondTry = false;
602 bool IsFilteredTemplateName = false;
603
604Corrected:
605 switch (Result.getResultKind()) {
606 case LookupResult::NotFound:
607 // If an unqualified-id is followed by a '(', then we have a function
608 // call.
609 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
610 // In C++, this is an ADL-only call.
611 // FIXME: Reference?
David Blaikie4e4d0842012-03-11 07:00:24 +0000612 if (getLangOpts().CPlusPlus)
Douglas Gregor312eadb2011-04-24 05:37:28 +0000613 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
614
615 // C90 6.3.2.2:
616 // If the expression that precedes the parenthesized argument list in a
617 // function call consists solely of an identifier, and if no
618 // declaration is visible for this identifier, the identifier is
619 // implicitly declared exactly as if, in the innermost block containing
620 // the function call, the declaration
621 //
622 // extern int identifier ();
623 //
624 // appeared.
625 //
626 // We also allow this in C99 as an extension.
627 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
628 Result.addDecl(D);
629 Result.resolveKind();
630 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
631 }
632 }
633
634 // In C, we first see whether there is a tag type by the same name, in
635 // which case it's likely that the user just forget to write "enum",
636 // "struct", or "union".
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000637 if (!getLangOpts().CPlusPlus && !SecondTry &&
638 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
639 break;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000640 }
641
642 // Perform typo correction to determine if there is another name that is
643 // close to this name.
Richard Smith05766812012-08-18 00:55:03 +0000644 if (!SecondTry && CCC) {
Douglas Gregor3a348c82011-07-14 04:54:23 +0000645 SecondTry = true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000646 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikied662a792011-10-19 22:56:21 +0000647 Result.getLookupKind(), S,
Richard Smith05766812012-08-18 00:55:03 +0000648 &SS, *CCC)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000649 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
650 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smith2d670972013-08-17 00:46:16 +0000651
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000652 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor3b887352011-04-27 04:48:22 +0000653 NamedDecl *UnderlyingFirstDecl
654 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikie4e4d0842012-03-11 07:00:24 +0000655 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000656 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000657 UnqualifiedDiag = diag::err_no_template_suggest;
658 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor3b887352011-04-27 04:48:22 +0000659 } else if (UnderlyingFirstDecl &&
660 (isa<TypeDecl>(UnderlyingFirstDecl) ||
661 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
662 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie30262b72013-03-21 21:35:15 +0000663 UnqualifiedDiag = diag::err_unknown_typename_suggest;
664 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
665 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000666
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000667 if (SS.isEmpty()) {
Richard Smith2d670972013-08-17 00:46:16 +0000668 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000669 } else {// FIXME: is this even reachable? Test it.
Richard Smith2d670972013-08-17 00:46:16 +0000670 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
671 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000672 Name->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000673 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
674 << Name << computeDeclContext(SS, false)
675 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000676 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000677
678 // Update the name, so that the caller has the new name.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000679 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smith2d670972013-08-17 00:46:16 +0000680
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000681 // Typo correction corrected to a keyword.
682 if (Corrected.isKeyword())
Richard Smith2d670972013-08-17 00:46:16 +0000683 return Name;
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000684
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000685 // Also update the LookupResult...
686 // FIXME: This should probably go away at some point
687 Result.clear();
688 Result.setLookupName(Corrected.getCorrection());
Richard Smith2d670972013-08-17 00:46:16 +0000689 if (FirstDecl)
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000690 Result.addDecl(FirstDecl);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000691
692 // If we found an Objective-C instance variable, let
693 // LookupInObjCMethod build the appropriate expression to
694 // reference the ivar.
695 // FIXME: This is a gross hack.
696 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
697 Result.clear();
698 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000699 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000700 }
701
702 goto Corrected;
703 }
704 }
705
706 // We failed to correct; just fall through and let the parser deal with it.
707 Result.suppressDiagnostics();
708 return NameClassification::Unknown();
709
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000710 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000711 // We performed name lookup into the current instantiation, and there were
712 // dependent bases, so we treat this result the same way as any other
713 // dependent nested-name-specifier.
714
715 // C++ [temp.res]p2:
716 // A name used in a template declaration or definition and that is
717 // dependent on a template-parameter is assumed not to name a type
718 // unless the applicable name lookup finds a type name or the name is
719 // qualified by the keyword typename.
720 //
721 // FIXME: If the next token is '<', we might want to ask the parser to
722 // perform some heroics to see if we actually have a
723 // template-argument-list, which would indicate a missing 'template'
724 // keyword here.
Richard Smith05766812012-08-18 00:55:03 +0000725 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
726 NameInfo, IsAddressOfOperand,
727 /*TemplateArgs=*/0);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000728 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000729
730 case LookupResult::Found:
731 case LookupResult::FoundOverloaded:
732 case LookupResult::FoundUnresolvedValue:
733 break;
734
735 case LookupResult::Ambiguous:
David Blaikie4e4d0842012-03-11 07:00:24 +0000736 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000737 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000738 // C++ [temp.local]p3:
739 // A lookup that finds an injected-class-name (10.2) can result in an
740 // ambiguity in certain cases (for example, if it is found in more than
741 // one base class). If all of the injected-class-names that are found
742 // refer to specializations of the same class template, and if the name
743 // is followed by a template-argument-list, the reference refers to the
744 // class template itself and not a specialization thereof, and is not
745 // ambiguous.
746 //
747 // This filtering can make an ambiguous result into an unambiguous one,
748 // so try again after filtering out template names.
749 FilterAcceptableTemplateNames(Result);
750 if (!Result.isAmbiguous()) {
751 IsFilteredTemplateName = true;
752 break;
753 }
754 }
755
756 // Diagnose the ambiguity and return an error.
757 return NameClassification::Error();
758 }
759
David Blaikie4e4d0842012-03-11 07:00:24 +0000760 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000761 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
762 // C++ [temp.names]p3:
763 // After name lookup (3.4) finds that a name is a template-name or that
764 // an operator-function-id or a literal- operator-id refers to a set of
765 // overloaded functions any member of which is a function template if
766 // this is followed by a <, the < is always taken as the delimiter of a
767 // template-argument-list and never as the less-than operator.
768 if (!IsFilteredTemplateName)
769 FilterAcceptableTemplateNames(Result);
770
Douglas Gregor3b887352011-04-27 04:48:22 +0000771 if (!Result.empty()) {
772 bool IsFunctionTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000773 bool IsVarTemplate;
Douglas Gregor3b887352011-04-27 04:48:22 +0000774 TemplateName Template;
775 if (Result.end() - Result.begin() > 1) {
776 IsFunctionTemplate = true;
777 Template = Context.getOverloadedTemplateName(Result.begin(),
778 Result.end());
779 } else {
780 TemplateDecl *TD
781 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
782 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000783 IsVarTemplate = isa<VarTemplateDecl>(TD);
784
Douglas Gregor3b887352011-04-27 04:48:22 +0000785 if (SS.isSet() && !SS.isInvalid())
786 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor312eadb2011-04-24 05:37:28 +0000787 /*TemplateKeyword=*/false,
Douglas Gregor3b887352011-04-27 04:48:22 +0000788 TD);
789 else
790 Template = TemplateName(TD);
791 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000792
Douglas Gregor3b887352011-04-27 04:48:22 +0000793 if (IsFunctionTemplate) {
794 // Function templates always go through overload resolution, at which
795 // point we'll perform the various checks (e.g., accessibility) we need
796 // to based on which function we selected.
797 Result.suppressDiagnostics();
798
799 return NameClassification::FunctionTemplate(Template);
800 }
Larisse Voufoef4579c2013-08-06 01:03:05 +0000801
802 return IsVarTemplate ? NameClassification::VarTemplate(Template)
803 : NameClassification::TypeTemplate(Template);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000804 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000805 }
Richard Smith05766812012-08-18 00:55:03 +0000806
Douglas Gregor3b887352011-04-27 04:48:22 +0000807 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000808 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
809 DiagnoseUseOfDecl(Type, NameLoc);
810 QualType T = Context.getTypeDeclType(Type);
Richard Smith05766812012-08-18 00:55:03 +0000811 if (SS.isNotEmpty())
812 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000813 return ParsedType::make(T);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000814 }
Richard Smith05766812012-08-18 00:55:03 +0000815
Douglas Gregor312eadb2011-04-24 05:37:28 +0000816 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
817 if (!Class) {
818 // FIXME: It's unfortunate that we don't have a Type node for handling this.
819 if (ObjCCompatibleAliasDecl *Alias
820 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
821 Class = Alias->getClassInterface();
822 }
823
824 if (Class) {
825 DiagnoseUseOfDecl(Class, NameLoc);
826
827 if (NextToken.is(tok::period)) {
828 // Interface. <something> is parsed as a property reference expression.
829 // Just return "unknown" as a fall-through for now.
830 Result.suppressDiagnostics();
831 return NameClassification::Unknown();
832 }
833
834 QualType T = Context.getObjCInterfaceType(Class);
835 return ParsedType::make(T);
836 }
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000837
Richard Smith05766812012-08-18 00:55:03 +0000838 // We can have a type template here if we're classifying a template argument.
839 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
840 return NameClassification::TypeTemplate(
841 TemplateName(cast<TemplateDecl>(FirstDecl)));
842
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000843 // Check for a tag type hidden by a non-type decl in a few cases where it
844 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidis99e9fe02013-05-07 19:54:28 +0000845 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
846 if ((NextToken.is(tok::identifier) ||
847 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
848 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
849 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
850 DiagnoseUseOfDecl(Type, NameLoc);
851 QualType T = Context.getTypeDeclType(Type);
852 if (SS.isNotEmpty())
853 return buildNestedType(*this, SS, T, NameLoc);
854 return ParsedType::make(T);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000855 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000856
Richard Smith05766812012-08-18 00:55:03 +0000857 if (FirstDecl->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000858 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor3b887352011-04-27 04:48:22 +0000859
Douglas Gregor312eadb2011-04-24 05:37:28 +0000860 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
861 return BuildDeclarationNameExpr(SS, Result, ADL);
862}
863
John McCall88232aa2009-08-18 00:00:49 +0000864// Determines the context to return to after temporarily entering a
865// context. This depends in an unnecessarily complicated way on the
866// exact ordering of callbacks from the parser.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000867DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000868
John McCall88232aa2009-08-18 00:00:49 +0000869 // Functions defined inline within classes aren't parsed until we've
870 // finished parsing the top-level class, so the top-level class is
871 // the context we'll need to return to.
872 if (isa<FunctionDecl>(DC)) {
873 DC = DC->getLexicalParent();
874
875 // A function not defined within a class will always return to its
876 // lexical context.
877 if (!isa<CXXRecordDecl>(DC))
878 return DC;
879
880 // A C++ inline method/friend is parsed *after* the topmost class
881 // it was declared in is fully parsed ("complete"); the topmost
882 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000883 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000884 DC = RD;
885
886 // Return the declaration context of the topmost class the inline method is
887 // declared in.
888 return DC;
889 }
890
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000891 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000892}
893
Douglas Gregor44b43212008-12-11 16:49:14 +0000894void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000895 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000896 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000897 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000898 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000899}
900
Chris Lattnerb048c982008-04-06 04:47:34 +0000901void Sema::PopDeclContext() {
902 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000903
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000904 CurContext = getContainingDC(CurContext);
John McCallacb70392010-07-23 22:45:07 +0000905 assert(CurContext && "Popped translation unit!");
Chris Lattner0ed844b2008-04-04 06:12:32 +0000906}
907
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000908/// EnterDeclaratorContext - Used when we must lookup names in the context
909/// of a declarator's nested name specifier.
John McCall7a1dc562009-12-19 10:49:29 +0000910///
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000911void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall7a1dc562009-12-19 10:49:29 +0000912 // C++0x [basic.lookup.unqual]p13:
913 // A name used in the definition of a static data member of class
914 // X (after the qualified-id of the static member) is looked up as
915 // if the name was used in a member function of X.
916 // C++0x [basic.lookup.unqual]p14:
917 // If a variable member of a namespace is defined outside of the
918 // scope of its namespace then any name used in the definition of
919 // the variable member (after the declarator-id) is looked up as
920 // if the definition of the variable member occurred in its
921 // namespace.
922 // Both of these imply that we should push a scope whose context
923 // is the semantic context of the declaration. We can't use
924 // PushDeclContext here because that context is not necessarily
925 // lexically contained in the current context. Fortunately,
926 // the containing scope should have the appropriate information.
927
928 assert(!S->getEntity() && "scope already has entity");
929
930#ifndef NDEBUG
931 Scope *Ancestor = S->getParent();
932 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
933 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
934#endif
935
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000936 CurContext = DC;
John McCall7a1dc562009-12-19 10:49:29 +0000937 S->setEntity(DC);
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000938}
939
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000940void Sema::ExitDeclaratorContext(Scope *S) {
John McCall7a1dc562009-12-19 10:49:29 +0000941 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000942
John McCall7a1dc562009-12-19 10:49:29 +0000943 // Switch back to the lexical context. The safety of this is
944 // enforced by an assert in EnterDeclaratorContext.
945 Scope *Ancestor = S->getParent();
946 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekf0d58612013-10-08 17:08:03 +0000947 CurContext = Ancestor->getEntity();
John McCall7a1dc562009-12-19 10:49:29 +0000948
949 // We don't need to do anything with the scope, which is going to
950 // disappear.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000951}
952
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000953
954void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
955 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
956 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
957 // We assume that the caller has already called
958 // ActOnReenterTemplateScope
959 FD = TFD->getTemplatedDecl();
960 }
961 if (!FD)
962 return;
963
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000964 // Same implementation as PushDeclContext, but enters the context
965 // from the lexical parent, rather than the top-level class.
966 assert(CurContext == FD->getLexicalParent() &&
967 "The next DeclContext should be lexically contained in the current one.");
968 CurContext = FD;
969 S->setEntity(CurContext);
970
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000971 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
972 ParmVarDecl *Param = FD->getParamDecl(P);
973 // If the parameter has an identifier, then add it to the scope
974 if (Param->getIdentifier()) {
975 S->AddDecl(Param);
976 IdResolver.AddDecl(Param);
977 }
978 }
979}
980
981
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000982void Sema::ActOnExitFunctionContext() {
983 // Same implementation as PopDeclContext, but returns to the lexical parent,
984 // rather than the top-level class.
985 assert(CurContext && "DeclContext imbalance!");
986 CurContext = CurContext->getLexicalParent();
987 assert(CurContext && "Popped translation unit!");
988}
989
990
Douglas Gregorf9201e02009-02-11 23:02:49 +0000991/// \brief Determine whether we allow overloading of the function
992/// PrevDecl with another declaration.
993///
994/// This routine determines whether overloading is possible, not
995/// whether some new function is actually an overload. It will return
996/// true in C++ (where we can always provide overloads) or, as an
997/// extension, in C when the previous function is already an
998/// overloaded function declaration or has the "overloadable"
999/// attribute.
John McCall68263142009-11-18 22:49:29 +00001000static bool AllowOverloadingOfFunction(LookupResult &Previous,
1001 ASTContext &Context) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001002 if (Context.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001003 return true;
1004
John McCall68263142009-11-18 22:49:29 +00001005 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001006 return true;
1007
John McCall68263142009-11-18 22:49:29 +00001008 return (Previous.getResultKind() == LookupResult::Found
1009 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregorf9201e02009-02-11 23:02:49 +00001010}
1011
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001012/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +00001013void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +00001014 // Move up the scope chain until we find the nearest enclosing
1015 // non-transparent context. The declaration will be introduced into this
1016 // scope.
Ted Kremenekf0d58612013-10-08 17:08:03 +00001017 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor074149e2009-01-05 19:45:36 +00001018 S = S->getParent();
1019
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001020 // Add scoped declarations into their context, so that they can be
1021 // found later. Declarations without a context won't be inserted
1022 // into any context.
John McCallab88d972009-08-31 22:39:49 +00001023 if (AddToContext)
1024 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001025
Richard Smitha41c97a2013-09-20 01:15:31 +00001026 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1027 // are function-local declarations.
1028 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregor6d0468b2011-10-09 22:57:49 +00001029 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smitha41c97a2013-09-20 01:15:31 +00001030 D->getLexicalDeclContext()->getRedeclContext()) &&
1031 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruth8761d682010-02-21 07:08:09 +00001032 return;
1033
1034 // Template instantiations should also not be pushed into scope.
1035 if (isa<FunctionDecl>(D) &&
1036 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregord04b1be2009-09-28 18:41:37 +00001037 return;
1038
John McCallf36e02d2009-10-09 21:13:30 +00001039 // If this replaces anything in the current scope,
1040 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1041 IEnd = IdResolver.end();
1042 for (; I != IEnd; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001043 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1044 S->RemoveDecl(*I);
John McCallf36e02d2009-10-09 21:13:30 +00001045 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001046
John McCallf36e02d2009-10-09 21:13:30 +00001047 // Should only need to replace one decl.
1048 break;
Douglas Gregor516ff432009-04-24 02:57:34 +00001049 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001050 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001051
John McCalld226f652010-08-21 09:40:31 +00001052 S->AddDecl(D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001053
1054 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1055 // Implicitly-generated labels may end up getting generated in an order that
1056 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1057 // the label at the appropriate place in the identifier chain.
1058 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregor1d2de762011-03-24 14:35:16 +00001059 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor250e7a72011-03-16 16:39:03 +00001060 if (IDC == CurContext) {
1061 if (!S->isDeclScope(*I))
1062 continue;
1063 } else if (IDC->Encloses(CurContext))
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001064 break;
1065 }
1066
Douglas Gregor250e7a72011-03-16 16:39:03 +00001067 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001068 } else {
1069 IdResolver.AddDecl(D);
1070 }
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001071}
1072
Douglas Gregoreee242f2011-10-27 09:33:13 +00001073void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1074 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1075 TUScope->AddDecl(D);
1076}
1077
Richard Smithdd9459f2013-08-13 18:18:50 +00001078bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001079 bool ExplicitInstantiationOrSpecialization) {
Nico Weber355a1662012-12-17 03:51:09 +00001080 return IdResolver.isDeclInScope(D, Ctx, S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001081 ExplicitInstantiationOrSpecialization);
Douglas Gregor2531c2d2009-09-28 00:47:05 +00001082}
1083
John McCall5f1e0942010-08-24 08:50:51 +00001084Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1085 DeclContext *TargetDC = DC->getPrimaryContext();
1086 do {
Ted Kremenekf0d58612013-10-08 17:08:03 +00001087 if (DeclContext *ScopeDC = S->getEntity())
John McCall5f1e0942010-08-24 08:50:51 +00001088 if (ScopeDC->getPrimaryContext() == TargetDC)
1089 return S;
1090 } while ((S = S->getParent()));
1091
1092 return 0;
1093}
1094
John McCall68263142009-11-18 22:49:29 +00001095static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1096 DeclContext*,
1097 ASTContext&);
1098
1099/// Filters out lookup results that don't fall within the given scope
1100/// as determined by isDeclInScope.
Richard Smith3e4c6c42011-05-05 21:57:07 +00001101void Sema::FilterLookupForScope(LookupResult &R,
1102 DeclContext *Ctx, Scope *S,
1103 bool ConsiderLinkage,
1104 bool ExplicitInstantiationOrSpecialization) {
John McCall68263142009-11-18 22:49:29 +00001105 LookupResult::Filter F = R.makeFilter();
1106 while (F.hasNext()) {
1107 NamedDecl *D = F.next();
1108
Richard Smith3e4c6c42011-05-05 21:57:07 +00001109 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall68263142009-11-18 22:49:29 +00001110 continue;
1111
1112 if (ConsiderLinkage &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00001113 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall68263142009-11-18 22:49:29 +00001114 continue;
1115
1116 F.erase();
1117 }
1118
1119 F.done();
1120}
1121
1122static bool isUsingDecl(NamedDecl *D) {
1123 return isa<UsingShadowDecl>(D) ||
1124 isa<UnresolvedUsingTypenameDecl>(D) ||
1125 isa<UnresolvedUsingValueDecl>(D);
1126}
1127
1128/// Removes using shadow declarations from the lookup results.
1129static void RemoveUsingDecls(LookupResult &R) {
1130 LookupResult::Filter F = R.makeFilter();
1131 while (F.hasNext())
1132 if (isUsingDecl(F.next()))
1133 F.erase();
1134
1135 F.done();
1136}
1137
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001138/// \brief Check for this common pattern:
1139/// @code
1140/// class S {
1141/// S(const S&); // DO NOT IMPLEMENT
1142/// void operator=(const S&); // DO NOT IMPLEMENT
1143/// };
1144/// @endcode
1145static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1146 // FIXME: Should check for private access too but access is set after we get
1147 // the decl here.
Sean Hunt10620eb2011-05-06 20:44:56 +00001148 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001149 return false;
1150
1151 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1152 return CD->isCopyConstructor();
Douglas Gregor27c08ab2010-09-27 22:06:20 +00001153 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1154 return Method->isCopyAssignmentOperator();
1155 return false;
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001156}
1157
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001158// We need this to handle
1159//
1160// typedef struct {
1161// void *foo() { return 0; }
1162// } A;
1163//
1164// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1165// for example. If 'A', foo will have external linkage. If we have '*A',
1166// foo will have no linkage. Since we can't know untill we get to the end
1167// of the typedef, this function finds out if D might have non external linkage.
1168// Callers should verify at the end of the TU if it D has external linkage or
1169// not.
1170bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1171 const DeclContext *DC = D->getDeclContext();
1172 while (!DC->isTranslationUnit()) {
1173 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1174 if (!RD->hasNameForLinkage())
1175 return true;
1176 }
1177 DC = DC->getParent();
1178 }
1179
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001180 return !D->isExternallyVisible();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001181}
1182
Eli Friedman39bd3712013-09-10 03:05:56 +00001183// FIXME: This needs to be refactored; some other isInMainFile users want
1184// these semantics.
1185static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1186 if (S.TUKind != TU_Complete)
1187 return false;
1188 return S.SourceMgr.isInMainFile(Loc);
1189}
1190
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001191bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1192 assert(D);
Argyrios Kyrtzidisf6d1d432010-08-13 18:42:29 +00001193
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001194 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1195 return false;
1196
1197 // Ignore class templates.
Chandler Carruthef9d09c2011-01-03 19:27:19 +00001198 if (D->getDeclContext()->isDependentContext() ||
1199 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001200 return false;
1201
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001202 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001203 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1204 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001205
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001206 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1207 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1208 return false;
1209 } else {
Eli Friedman39bd3712013-09-10 03:05:56 +00001210 // 'static inline' functions are defined in headers; don't warn.
1211 if (FD->isInlineSpecified() &&
1212 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001213 return false;
1214 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001215
Sean Hunt10620eb2011-05-06 20:44:56 +00001216 if (FD->doesThisDeclarationHaveABody() &&
John McCall82b96592010-10-27 01:41:35 +00001217 Context.DeclMustBeEmitted(FD))
1218 return false;
John McCall82b96592010-10-27 01:41:35 +00001219 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman39bd3712013-09-10 03:05:56 +00001220 // Constants and utility variables are defined in headers with internal
1221 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1222 // like "inline".)
1223 if (!isMainFileLoc(*this, VD->getLocation()))
1224 return false;
1225
Eli Friedman39bd3712013-09-10 03:05:56 +00001226 if (Context.DeclMustBeEmitted(VD))
John McCall82b96592010-10-27 01:41:35 +00001227 return false;
1228
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001229 if (VD->isStaticDataMember() &&
1230 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1231 return false;
John McCall82b96592010-10-27 01:41:35 +00001232 } else {
1233 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001234 }
1235
John McCall82b96592010-10-27 01:41:35 +00001236 // Only warn for unused decls internal to the translation unit.
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001237 return mightHaveNonExternalLinkage(D);
John McCall82b96592010-10-27 01:41:35 +00001238}
1239
1240void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001241 if (!D)
1242 return;
1243
1244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001245 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001246 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1247 return; // First should already be in the vector.
1248 }
1249
1250 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001251 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001252 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1253 return; // First should already be in the vector.
1254 }
1255
David Blaikie7f7c42b2012-05-26 05:35:39 +00001256 if (ShouldWarnIfUnusedFileScopedDecl(D))
1257 UnusedFileScopedDecls.push_back(D);
1258}
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00001259
Anders Carlsson99a000e2009-11-07 07:18:14 +00001260static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +00001261 if (D->isInvalidDecl())
1262 return false;
1263
Eli Friedmandd9d6452012-01-13 23:41:25 +00001264 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001265 return false;
John McCall86ff3082010-02-04 22:26:26 +00001266
Chris Lattner57ad3782011-02-17 20:34:02 +00001267 if (isa<LabelDecl>(D))
1268 return true;
1269
John McCall86ff3082010-02-04 22:26:26 +00001270 // White-list anything that isn't a local variable.
1271 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1272 !D->getDeclContext()->isFunctionOrMethod())
1273 return false;
1274
1275 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001276 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +00001277
1278 // White-list anything with an __attribute__((unused)) type.
1279 QualType Ty = VD->getType();
1280
1281 // Only look at the outermost level of typedef.
Douglas Gregor2c8e81e2012-09-14 05:10:40 +00001282 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallaec58602010-03-31 02:47:45 +00001283 if (TT->getDecl()->hasAttr<UnusedAttr>())
1284 return false;
1285 }
1286
Douglas Gregor5764f612010-05-08 23:05:03 +00001287 // If we failed to complete the type for some reason, or if the type is
1288 // dependent, don't diagnose the variable.
1289 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +00001290 return false;
1291
John McCallaec58602010-03-31 02:47:45 +00001292 if (const TagType *TT = Ty->getAs<TagType>()) {
1293 const TagDecl *Tag = TT->getDecl();
1294 if (Tag->hasAttr<UnusedAttr>())
1295 return false;
1296
1297 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001298 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001299 return false;
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001300
1301 if (const Expr *Init = VD->getInit()) {
David Blaikie39e17762012-10-24 21:29:06 +00001302 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1303 Init = Cleanups->getSubExpr();
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001304 const CXXConstructExpr *Construct =
1305 dyn_cast<CXXConstructExpr>(Init);
1306 if (Construct && !Construct->isElidable()) {
1307 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001308 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001309 return false;
1310 }
1311 }
Anders Carlssonf7613d52009-11-07 07:26:56 +00001312 }
1313 }
John McCallaec58602010-03-31 02:47:45 +00001314
1315 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +00001316 }
1317
John McCall86ff3082010-02-04 22:26:26 +00001318 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +00001319}
1320
Anna Zaksd5612a22011-07-28 20:52:06 +00001321static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1322 FixItHint &Hint) {
1323 if (isa<LabelDecl>(D)) {
1324 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001325 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaksd5612a22011-07-28 20:52:06 +00001326 if (AfterColon.isInvalid())
1327 return;
1328 Hint = FixItHint::CreateRemoval(CharSourceRange::
1329 getCharRange(D->getLocStart(), AfterColon));
1330 }
1331 return;
1332}
1333
Chris Lattner337e5502011-02-18 01:27:55 +00001334/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1335/// unless they are marked attr(unused).
Douglas Gregor5764f612010-05-08 23:05:03 +00001336void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaksd5612a22011-07-28 20:52:06 +00001337 FixItHint Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001338 if (!ShouldDiagnoseUnusedDecl(D))
1339 return;
1340
Anna Zaksd5612a22011-07-28 20:52:06 +00001341 GenerateFixForUnusedDecl(D, Context, Hint);
1342
Chris Lattner57ad3782011-02-17 20:34:02 +00001343 unsigned DiagID;
Douglas Gregor5764f612010-05-08 23:05:03 +00001344 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattner57ad3782011-02-17 20:34:02 +00001345 DiagID = diag::warn_unused_exception_param;
1346 else if (isa<LabelDecl>(D))
1347 DiagID = diag::warn_unused_label;
Douglas Gregor5764f612010-05-08 23:05:03 +00001348 else
Chris Lattner57ad3782011-02-17 20:34:02 +00001349 DiagID = diag::warn_unused_variable;
1350
Anna Zaksd5612a22011-07-28 20:52:06 +00001351 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001352}
1353
Chris Lattner337e5502011-02-18 01:27:55 +00001354static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1355 // Verify that we have no forward references left. If so, there was a goto
1356 // or address of a label taken, but no definition of it. Label fwd
1357 // definitions are indicated with a null substmt.
1358 if (L->getStmt() == 0)
1359 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1360}
1361
Steve Naroffb216c882007-10-09 22:01:59 +00001362void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +00001363 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +00001364 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001365 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001366
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1368 I != E; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001369 Decl *TmpD = (*I);
Steve Naroffc752d042007-09-13 18:10:37 +00001370 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001371
Douglas Gregor44b43212008-12-11 16:49:14 +00001372 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1373 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001374
Douglas Gregor44b43212008-12-11 16:49:14 +00001375 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +00001376
Douglas Gregorb5352cf2009-10-08 21:35:42 +00001377 // Diagnose unused variables in this scope.
Matt Beaumont-Gay59d8ccb2013-03-28 21:46:45 +00001378 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor5764f612010-05-08 23:05:03 +00001379 DiagnoseUnusedDecl(D);
1380
Chris Lattner337e5502011-02-18 01:27:55 +00001381 // If this was a forward reference to a label, verify it was defined.
1382 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1383 CheckPoppedLabel(LD, *this);
1384
Douglas Gregor44b43212008-12-11 16:49:14 +00001385 // Remove this name from our lexical scope.
1386 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 }
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00001388 DiagnoseUnusedBackingIvarInAccessor(S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001389}
1390
James Molloy16f1f712012-02-29 10:24:19 +00001391void Sema::ActOnStartFunctionDeclarator() {
1392 ++InFunctionDeclarator;
1393}
1394
1395void Sema::ActOnEndFunctionDeclarator() {
1396 assert(InFunctionDeclarator);
1397 --InFunctionDeclarator;
1398}
1399
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001400/// \brief Look for an Objective-C class in the translation unit.
1401///
1402/// \param Id The name of the Objective-C class we're looking for. If
1403/// typo-correction fixes this name, the Id will be updated
1404/// to the fixed name.
1405///
1406/// \param IdLoc The location of the name in the translation unit.
1407///
James Dennett16ae9de2012-06-22 10:16:05 +00001408/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001409/// if there is no class with the given name.
1410///
1411/// \returns The declaration of the named Objective-C class, or NULL if the
1412/// class could not be found.
1413ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1414 SourceLocation IdLoc,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001415 bool DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001416 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1417 // creation from this context.
1418 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1419
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001420 if (!IDecl && DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001421 // Perform typo correction at the given location, but only if we
1422 // find an Objective-C class name.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001423 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1424 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1425 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001426 Validator)) {
Richard Smith2d670972013-08-17 00:46:16 +00001427 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001428 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001429 Id = IDecl->getIdentifier();
1430 }
1431 }
Fariborz Jahanian3306f962012-01-12 00:18:35 +00001432 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1433 // This routine must always return a class definition, if any.
1434 if (Def && Def->getDefinition())
1435 Def = Def->getDefinition();
1436 return Def;
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001437}
1438
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001439/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1440/// from S, where a non-field would be declared. This routine copes
1441/// with the difference between C and C++ scoping rules in structs and
1442/// unions. For example, the following code is well-formed in C but
1443/// ill-formed in C++:
1444/// @code
1445/// struct S6 {
1446/// enum { BAR } e;
1447/// };
Mike Stump1eb44332009-09-09 15:08:12 +00001448///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001449/// void test_S6() {
1450/// struct S6 a;
1451/// a.e = BAR;
1452/// }
1453/// @endcode
1454/// For the declaration of BAR, this routine will return a different
1455/// scope. The scope S will be the scope of the unnamed enumeration
1456/// within S6. In C++, this routine will return the scope associated
1457/// with S6, because the enumeration's scope is a transparent
1458/// context but structures can contain non-field names. In C, this
1459/// routine will return the translation unit scope, since the
1460/// enumeration's scope is a transparent context and structures cannot
1461/// contain non-field names.
1462Scope *Sema::getNonFieldDeclScope(Scope *S) {
1463 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +00001464 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001465 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001466 S = S->getParent();
1467 return S;
1468}
1469
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001470/// \brief Looks up the declaration of "struct objc_super" and
1471/// saves it for later use in building builtin declaration of
1472/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1473/// pre-existing declaration exists no action takes place.
1474static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1475 IdentifierInfo *II) {
1476 if (!II->isStr("objc_msgSendSuper"))
1477 return;
1478 ASTContext &Context = ThisSema.Context;
1479
1480 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1481 SourceLocation(), Sema::LookupTagName);
1482 ThisSema.LookupName(Result, S);
1483 if (Result.getResultKind() == LookupResult::Found)
1484 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1485 Context.setObjCSuperType(Context.getTagDeclType(TD));
1486}
1487
Douglas Gregor3e41d602009-02-13 23:20:09 +00001488/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1489/// file scope. lazily create a decl for it. ForRedeclaration is true
1490/// if we're creating this built-in in anticipation of redeclaring the
1491/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001492NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001493 Scope *S, bool ForRedeclaration,
1494 SourceLocation Loc) {
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001495 LookupPredefedObjCSuperType(*this, S, II);
1496
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 Builtin::ID BID = (Builtin::ID)bid;
1498
Chris Lattner86df27b2009-06-14 00:45:47 +00001499 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001500 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001501 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +00001502 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001503 // Okay
1504 break;
1505
Mike Stumpf711c412009-07-28 23:57:15 +00001506 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001507 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001508 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001509 << Context.BuiltinInfo.GetName(BID);
1510 return 0;
Mike Stump782fa302009-07-28 02:25:19 +00001511
Mike Stumpf711c412009-07-28 23:57:15 +00001512 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +00001513 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001514 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stump782fa302009-07-28 02:25:19 +00001515 << Context.BuiltinInfo.GetName(BID);
1516 return 0;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00001517
1518 case ASTContext::GE_Missing_ucontext:
1519 if (ForRedeclaration)
1520 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1521 << Context.BuiltinInfo.GetName(BID);
1522 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001523 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00001524
1525 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1526 Diag(Loc, diag::ext_implicit_lib_function_decl)
1527 << Context.BuiltinInfo.GetName(BID)
1528 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +00001529 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001530 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikied6471f72011-09-25 23:23:43 +00001531 != DiagnosticsEngine::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +00001532 Diag(Loc, diag::note_please_include_header)
1533 << Context.BuiltinInfo.getHeaderName(BID)
1534 << Context.BuiltinInfo.GetName(BID);
1535 }
1536
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +00001537 FunctionDecl *New = FunctionDecl::Create(Context,
1538 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001539 Loc, Loc, II, R, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001540 SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001541 false,
Douglas Gregor2224f842009-02-25 16:33:18 +00001542 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001543 New->setImplicit();
1544
Chris Lattner95e2c712008-05-05 22:18:14 +00001545 // Create Decl objects for each parameter, adding them to the
1546 // FunctionDecl.
John McCallf4c73712011-01-19 06:33:43 +00001547 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001548 SmallVector<ParmVarDecl*, 16> Params;
John McCallfb44de92011-05-01 22:35:37 +00001549 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1550 ParmVarDecl *parm =
1551 ParmVarDecl::Create(Context, New, SourceLocation(),
1552 SourceLocation(), 0,
1553 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001554 SC_None, 0);
John McCallfb44de92011-05-01 22:35:37 +00001555 parm->setScopeInfo(0, i);
1556 Params.push_back(parm);
1557 }
David Blaikie4278c652011-09-21 18:16:56 +00001558 New->setParams(Params);
Chris Lattner95e2c712008-05-05 22:18:14 +00001559 }
Mike Stump1eb44332009-09-09 15:08:12 +00001560
1561 AddKnownFunctionAttributes(New);
1562
Chris Lattner7f925cc2008-04-11 07:00:53 +00001563 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001564 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1565 // relate Scopes to DeclContexts, and probably eliminate CurContext
1566 // entirely, but we're not there yet.
1567 DeclContext *SavedContext = CurContext;
1568 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001569 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001570 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 return New;
1572}
1573
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001574/// \brief Filter out any previous declarations that the given declaration
1575/// should not consider because they are not permitted to conflict, e.g.,
1576/// because they come from hidden sub-modules and do not refer to the same
1577/// entity.
1578static void filterNonConflictingPreviousDecls(ASTContext &context,
1579 NamedDecl *decl,
1580 LookupResult &previous){
1581 // This is only interesting when modules are enabled.
1582 if (!context.getLangOpts().Modules)
1583 return;
1584
1585 // Empty sets are uninteresting.
1586 if (previous.empty())
1587 return;
1588
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001589 LookupResult::Filter filter = previous.makeFilter();
1590 while (filter.hasNext()) {
1591 NamedDecl *old = filter.next();
1592
1593 // Non-hidden declarations are never ignored.
1594 if (!old->isHidden())
1595 continue;
1596
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001597 if (!old->isExternallyVisible())
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001598 filter.erase();
1599 }
1600
1601 filter.done();
1602}
1603
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001604bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1605 QualType OldType;
1606 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1607 OldType = OldTypedef->getUnderlyingType();
1608 else
1609 OldType = Context.getTypeDeclType(Old);
1610 QualType NewType = New->getUnderlyingType();
1611
Douglas Gregorec3bd722012-01-11 22:33:48 +00001612 if (NewType->isVariablyModifiedType()) {
1613 // Must not redefine a typedef with a variably-modified type.
1614 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1615 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1616 << Kind << NewType;
1617 if (Old->getLocation().isValid())
1618 Diag(Old->getLocation(), diag::note_previous_definition);
1619 New->setInvalidDecl();
1620 return true;
1621 }
1622
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001623 if (OldType != NewType &&
1624 !OldType->isDependentType() &&
1625 !NewType->isDependentType() &&
Douglas Gregorec3bd722012-01-11 22:33:48 +00001626 !Context.hasSameType(OldType, NewType)) {
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001627 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1628 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1629 << Kind << NewType << OldType;
1630 if (Old->getLocation().isValid())
1631 Diag(Old->getLocation(), diag::note_previous_definition);
1632 New->setInvalidDecl();
1633 return true;
1634 }
1635 return false;
1636}
1637
Richard Smith162e1c12011-04-15 14:24:37 +00001638/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregorcda9c672009-02-16 17:45:42 +00001639/// same name and scope as a previous declaration 'Old'. Figure out
1640/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +00001641/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001642///
Richard Smith162e1c12011-04-15 14:24:37 +00001643void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall68263142009-11-18 22:49:29 +00001644 // If the new decl is known invalid already, don't bother doing any
1645 // merging checks.
1646 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Steve Naroff2b255c42008-09-09 14:32:20 +00001648 // Allow multiple definitions for ObjC built-in typedefs.
1649 // FIXME: Verify the underlying types are equivalent!
David Blaikie4e4d0842012-03-11 07:00:24 +00001650 if (getLangOpts().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +00001651 const IdentifierInfo *TypeID = New->getIdentifier();
1652 switch (TypeID->getLength()) {
1653 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +00001654 case 2:
Fariborz Jahanian0cd00be2012-05-14 22:48:56 +00001655 {
1656 if (!TypeID->isStr("id"))
1657 break;
1658 QualType T = New->getUnderlyingType();
1659 if (!T->isPointerType())
1660 break;
1661 if (!T->isVoidPointerType()) {
1662 QualType PT = T->getAs<PointerType>()->getPointeeType();
1663 if (!PT->isStructureType())
1664 break;
1665 }
1666 Context.setObjCIdRedefinitionType(T);
1667 // Install the built-in type for 'id', ignoring the current definition.
1668 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1669 return;
1670 }
Chris Lattner2bac0f62008-11-20 05:41:43 +00001671 case 5:
1672 if (!TypeID->isStr("Class"))
1673 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001674 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff14108da2009-07-10 23:34:53 +00001675 // Install the built-in type for 'Class', ignoring the current definition.
1676 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001677 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +00001678 case 3:
1679 if (!TypeID->isStr("SEL"))
1680 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001681 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001682 // Install the built-in type for 'SEL', ignoring the current definition.
1683 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001684 return;
Steve Naroff2b255c42008-09-09 14:32:20 +00001685 }
1686 // Fall through - the typedef name was not a builtin type.
1687 }
John McCall68263142009-11-18 22:49:29 +00001688
Douglas Gregor66973122009-01-28 17:15:10 +00001689 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +00001690 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1691 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +00001692 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001693 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001694
1695 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001696 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00001697 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +00001698
Chris Lattnereaaebc72009-04-25 08:06:05 +00001699 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 }
Douglas Gregor66973122009-01-28 17:15:10 +00001701
John McCall68263142009-11-18 22:49:29 +00001702 // If the old declaration is invalid, just give up here.
1703 if (Old->isInvalidDecl())
1704 return New->setInvalidDecl();
1705
Chris Lattner99cb9972008-07-25 18:44:27 +00001706 // If the typedef types are not identical, reject them in all languages and
1707 // with any extensions enabled.
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001708 if (isIncompatibleTypedef(Old, New))
1709 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Justin Bogner2dd68de2013-10-08 00:19:09 +00001711 // The types match. Link up the redeclaration chain and merge attributes if
1712 // the old declaration was a typedef.
1713 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001714 New->setPreviousDecl(Typedef);
Justin Bogner2dd68de2013-10-08 00:19:09 +00001715 mergeDeclAttributes(New, Old);
1716 }
Eli Friedman9ec40992013-07-16 02:07:49 +00001717
David Blaikie4e4d0842012-03-11 07:00:24 +00001718 if (getLangOpts().MicrosoftExt)
Chris Lattnereaaebc72009-04-25 08:06:05 +00001719 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +00001720
David Blaikie4e4d0842012-03-11 07:00:24 +00001721 if (getLangOpts().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +00001722 // C++ [dcl.typedef]p2:
1723 // In a given non-class scope, a typedef specifier can be used to
1724 // redefine the name of any type declared in that scope to refer
1725 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +00001726 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +00001727 return;
Douglas Gregor93dda722010-01-11 21:54:40 +00001728
1729 // C++0x [dcl.typedef]p4:
1730 // In a given class scope, a typedef specifier can be used to redefine
1731 // any class-name declared in that scope that is not also a typedef-name
1732 // to refer to the type to which it already refers.
1733 //
1734 // This wording came in via DR424, which was a correction to the
1735 // wording in DR56, which accidentally banned code like:
1736 //
1737 // struct S {
1738 // typedef struct A { } A;
1739 // };
1740 //
1741 // in the C++03 standard. We implement the C++0x semantics, which
1742 // allow the above but disallow
1743 //
1744 // struct S {
1745 // typedef int I;
1746 // typedef int I;
1747 // };
1748 //
1749 // since that was the intent of DR56.
Richard Smith162e1c12011-04-15 14:24:37 +00001750 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +00001751 return;
1752
Chris Lattner32b06752009-04-17 22:04:20 +00001753 Diag(New->getLocation(), diag::err_redefinition)
1754 << New->getDeclName();
1755 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001756 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +00001757 }
Eli Friedman54ecfce2008-06-11 06:20:39 +00001758
Douglas Gregorc0004df2012-01-11 04:25:01 +00001759 // Modules always permit redefinition of typedefs, as does C11.
David Blaikie4e4d0842012-03-11 07:00:24 +00001760 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregorc02d62f2012-01-09 15:36:04 +00001761 return;
1762
Chris Lattner32b06752009-04-17 22:04:20 +00001763 // If we have a redefinition of a typedef in C, emit a warning. This warning
1764 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +00001765 // -Wtypedef-redefinition. If either the original or the redefinition is
1766 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00001767 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +00001768 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1769 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +00001770 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Chris Lattner32b06752009-04-17 22:04:20 +00001772 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1773 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001774 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001775 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001776}
1777
Chris Lattner6b6b5372008-06-26 18:38:35 +00001778/// DeclhasAttr - returns true if decl Declaration already has the target
1779/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00001780static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001781DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola3b294362012-05-06 19:56:25 +00001782 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1783 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1784 // responsible for making sure they are consistent.
1785 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1786 if (AA)
1787 return false;
1788
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001789 // The following thread safety attributes can also be duplicated.
1790 switch (A->getKind()) {
1791 case attr::ExclusiveLocksRequired:
1792 case attr::SharedLocksRequired:
1793 case attr::LocksExcluded:
1794 case attr::ExclusiveLockFunction:
1795 case attr::SharedLockFunction:
1796 case attr::UnlockFunction:
1797 case attr::ExclusiveTrylockFunction:
1798 case attr::SharedTrylockFunction:
1799 case attr::GuardedBy:
1800 case attr::PtGuardedBy:
1801 case attr::AcquiredBefore:
1802 case attr::AcquiredAfter:
1803 return false;
DeLesley Hutchins6c500b12012-10-12 21:49:04 +00001804 default:
1805 ;
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001806 }
1807
Sean Huntcf807c42010-08-18 23:23:40 +00001808 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001809 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Sean Huntcf807c42010-08-18 23:23:40 +00001810 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1811 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001812 if (Ann) {
1813 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1814 return true;
1815 continue;
1816 }
Sean Huntcf807c42010-08-18 23:23:40 +00001817 // FIXME: Don't hardcode this check
1818 if (OA && isa<OwnershipAttr>(*i))
1819 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001820 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001821 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001822
1823 return false;
1824}
1825
Richard Smith671b3212013-02-22 04:55:39 +00001826static bool isAttributeTargetADefinition(Decl *D) {
1827 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1828 return VD->isThisDeclarationADefinition();
1829 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1830 return TD->isCompleteDefinition() || TD->isBeingDefined();
1831 return true;
1832}
1833
1834/// Merge alignment attributes from \p Old to \p New, taking into account the
1835/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1836///
1837/// \return \c true if any attributes were added to \p New.
1838static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1839 // Look for alignas attributes on Old, and pick out whichever attribute
1840 // specifies the strictest alignment requirement.
1841 AlignedAttr *OldAlignasAttr = 0;
1842 AlignedAttr *OldStrictestAlignAttr = 0;
1843 unsigned OldAlign = 0;
1844 for (specific_attr_iterator<AlignedAttr>
1845 I = Old->specific_attr_begin<AlignedAttr>(),
1846 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1847 // FIXME: We have no way of representing inherited dependent alignments
1848 // in a case like:
1849 // template<int A, int B> struct alignas(A) X;
1850 // template<int A, int B> struct alignas(B) X {};
1851 // For now, we just ignore any alignas attributes which are not on the
1852 // definition in such a case.
1853 if (I->isAlignmentDependent())
1854 return false;
1855
1856 if (I->isAlignas())
1857 OldAlignasAttr = *I;
1858
1859 unsigned Align = I->getAlignment(S.Context);
1860 if (Align > OldAlign) {
1861 OldAlign = Align;
1862 OldStrictestAlignAttr = *I;
1863 }
1864 }
1865
1866 // Look for alignas attributes on New.
1867 AlignedAttr *NewAlignasAttr = 0;
1868 unsigned NewAlign = 0;
1869 for (specific_attr_iterator<AlignedAttr>
1870 I = New->specific_attr_begin<AlignedAttr>(),
1871 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1872 if (I->isAlignmentDependent())
1873 return false;
1874
1875 if (I->isAlignas())
1876 NewAlignasAttr = *I;
1877
1878 unsigned Align = I->getAlignment(S.Context);
1879 if (Align > NewAlign)
1880 NewAlign = Align;
1881 }
1882
1883 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1884 // Both declarations have 'alignas' attributes. We require them to match.
1885 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1886 // fall short. (If two declarations both have alignas, they must both match
1887 // every definition, and so must match each other if there is a definition.)
1888
1889 // If either declaration only contains 'alignas(0)' specifiers, then it
1890 // specifies the natural alignment for the type.
1891 if (OldAlign == 0 || NewAlign == 0) {
1892 QualType Ty;
1893 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1894 Ty = VD->getType();
1895 else
1896 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1897
1898 if (OldAlign == 0)
1899 OldAlign = S.Context.getTypeAlign(Ty);
1900 if (NewAlign == 0)
1901 NewAlign = S.Context.getTypeAlign(Ty);
1902 }
1903
1904 if (OldAlign != NewAlign) {
1905 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1906 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1907 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1908 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1909 }
1910 }
1911
1912 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1913 // C++11 [dcl.align]p6:
1914 // if any declaration of an entity has an alignment-specifier,
1915 // every defining declaration of that entity shall specify an
1916 // equivalent alignment.
1917 // C11 6.7.5/7:
1918 // If the definition of an object does not have an alignment
1919 // specifier, any other declaration of that object shall also
1920 // have no alignment specifier.
1921 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1922 << OldAlignasAttr->isC11();
1923 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1924 << OldAlignasAttr->isC11();
1925 }
1926
1927 bool AnyAdded = false;
1928
1929 // Ensure we have an attribute representing the strictest alignment.
1930 if (OldAlign > NewAlign) {
1931 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1932 Clone->setInherited(true);
1933 New->addAttr(Clone);
1934 AnyAdded = true;
1935 }
1936
1937 // Ensure we have an alignas attribute if the old declaration had one.
1938 if (OldAlignasAttr && !NewAlignasAttr &&
1939 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1940 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1941 Clone->setInherited(true);
1942 New->addAttr(Clone);
1943 AnyAdded = true;
1944 }
1945
1946 return AnyAdded;
1947}
1948
1949static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1950 bool Override) {
Rafael Espindola599f1b72012-05-13 03:25:18 +00001951 InheritableAttr *NewAttr = NULL;
Michael Han51d8c522013-01-24 16:46:58 +00001952 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola838dc592013-01-12 06:42:30 +00001953 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001954 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1955 AA->getIntroduced(), AA->getDeprecated(),
1956 AA->getObsoleted(), AA->getUnavailable(),
1957 AA->getMessage(), Override,
John McCalld4c3d662013-02-20 01:54:26 +00001958 AttrSpellingListIndex);
Richard Smith671b3212013-02-22 04:55:39 +00001959 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1960 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1961 AttrSpellingListIndex);
1962 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1963 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1964 AttrSpellingListIndex);
Rafael Espindola838dc592013-01-12 06:42:30 +00001965 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001966 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1967 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001968 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001969 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1970 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001971 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001972 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1973 FA->getFormatIdx(), FA->getFirstArg(),
1974 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001975 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001976 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1977 AttrSpellingListIndex);
1978 else if (isa<AlignedAttr>(Attr))
1979 // AlignedAttrs are handled separately, because we need to handle all
1980 // such attributes on a declaration at the same time.
1981 NewAttr = 0;
Rafael Espindola599f1b72012-05-13 03:25:18 +00001982 else if (!DeclHasAttr(D, Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001983 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindola98ae8342012-05-10 02:50:16 +00001984
Rafael Espindola599f1b72012-05-13 03:25:18 +00001985 if (NewAttr) {
Rafael Espindola98ae8342012-05-10 02:50:16 +00001986 NewAttr->setInherited(true);
1987 D->addAttr(NewAttr);
1988 return true;
1989 }
1990
1991 return false;
1992}
1993
Rafael Espindola4b044c62012-07-15 01:05:36 +00001994static const Decl *getDefinition(const Decl *D) {
1995 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola3f664062012-05-18 01:47:00 +00001996 return TD->getDefinition();
Rafael Espindolab1c0e202013-10-22 21:39:03 +00001997 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1998 const VarDecl *Def = VD->getDefinition();
1999 if (Def)
2000 return Def;
2001 return VD->getActingDefinition();
2002 }
Rafael Espindola4b044c62012-07-15 01:05:36 +00002003 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola3f664062012-05-18 01:47:00 +00002004 const FunctionDecl* Def;
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002005 if (FD->isDefined(Def))
Rafael Espindola3f664062012-05-18 01:47:00 +00002006 return Def;
2007 }
2008 return NULL;
2009}
2010
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002011static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2012 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2013 I != E; ++I) {
2014 Attr *Attribute = *I;
2015 if (Attribute->getKind() == Kind)
2016 return true;
2017 }
2018 return false;
2019}
2020
2021/// checkNewAttributesAfterDef - If we already have a definition, check that
2022/// there are no new attributes in this declaration.
2023static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2024 if (!New->hasAttrs())
2025 return;
2026
2027 const Decl *Def = getDefinition(Old);
2028 if (!Def || Def == New)
2029 return;
2030
2031 AttrVec &NewAttributes = New->getAttrs();
2032 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2033 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002034
2035 if (isa<AliasAttr>(NewAttribute)) {
2036 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2037 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2038 else {
2039 VarDecl *VD = cast<VarDecl>(New);
2040 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2041 VarDecl::TentativeDefinition
2042 ? diag::err_alias_after_tentative
2043 : diag::err_redefinition;
2044 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2045 S.Diag(Def->getLocation(), diag::note_previous_definition);
2046 VD->setInvalidDecl();
2047 }
2048 ++I;
2049 continue;
2050 }
2051
2052 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2053 // Tentative definitions are only interesting for the alias check above.
2054 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2055 ++I;
2056 continue;
2057 }
2058 }
2059
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002060 if (hasAttribute(Def, NewAttribute->getKind())) {
2061 ++I;
2062 continue; // regular attr merging will take care of validating this.
2063 }
Richard Smith671b3212013-02-22 04:55:39 +00002064
Richard Smith7586a6e2013-01-30 05:45:05 +00002065 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smith671b3212013-02-22 04:55:39 +00002066 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smith7586a6e2013-01-30 05:45:05 +00002067 ++I;
2068 continue;
Richard Smith671b3212013-02-22 04:55:39 +00002069 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2070 if (AA->isAlignas()) {
2071 // C++11 [dcl.align]p6:
2072 // if any declaration of an entity has an alignment-specifier,
2073 // every defining declaration of that entity shall specify an
2074 // equivalent alignment.
2075 // C11 6.7.5/7:
2076 // If the definition of an object does not have an alignment
2077 // specifier, any other declaration of that object shall also
2078 // have no alignment specifier.
2079 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2080 << AA->isC11();
2081 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2082 << AA->isC11();
2083 NewAttributes.erase(NewAttributes.begin() + I);
2084 --E;
2085 continue;
2086 }
Richard Smith7586a6e2013-01-30 05:45:05 +00002087 }
Richard Smith671b3212013-02-22 04:55:39 +00002088
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002089 S.Diag(NewAttribute->getLocation(),
2090 diag::warn_attribute_precede_definition);
2091 S.Diag(Def->getLocation(), diag::note_previous_definition);
2092 NewAttributes.erase(NewAttributes.begin() + I);
2093 --E;
2094 }
2095}
2096
John McCalleca5d222011-03-02 04:00:57 +00002097/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindola51be6e32013-01-08 22:04:34 +00002098void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002099 AvailabilityMergeKind AMK) {
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002100 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2101 UsedAttr *NewAttr = OldAttr->clone(Context);
2102 NewAttr->setInherited(true);
2103 New->addAttr(NewAttr);
2104 }
2105
Richard Smith3a2b7a12013-01-28 22:42:45 +00002106 if (!Old->hasAttrs() && !New->hasAttrs())
2107 return;
2108
Rafael Espindola3f664062012-05-18 01:47:00 +00002109 // attributes declared post-definition are currently ignored
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002110 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola3f664062012-05-18 01:47:00 +00002111
Douglas Gregor27c6da22012-01-01 20:30:41 +00002112 if (!Old->hasAttrs())
Sean Huntcf807c42010-08-18 23:23:40 +00002113 return;
John McCalleca5d222011-03-02 04:00:57 +00002114
Douglas Gregor27c6da22012-01-01 20:30:41 +00002115 bool foundAny = New->hasAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002116
Sean Huntcf807c42010-08-18 23:23:40 +00002117 // Ensure that any moving of objects within the allocated map is done before
2118 // we process them.
Douglas Gregor27c6da22012-01-01 20:30:41 +00002119 if (!foundAny) New->setAttrs(AttrVec());
John McCalleca5d222011-03-02 04:00:57 +00002120
Peter Collingbournea97d70b2011-01-21 02:08:36 +00002121 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor27c6da22012-01-01 20:30:41 +00002122 i = Old->specific_attr_begin<InheritableAttr>(),
2123 e = Old->specific_attr_end<InheritableAttr>();
2124 i != e; ++i) {
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002125 bool Override = false;
Douglas Gregorc193dd82011-09-23 20:23:42 +00002126 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002127 if (isa<DeprecatedAttr>(*i) ||
2128 isa<UnavailableAttr>(*i) ||
2129 isa<AvailabilityAttr>(*i)) {
2130 switch (AMK) {
2131 case AMK_None:
2132 continue;
John McCall6c2c2502011-07-22 02:45:48 +00002133
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002134 case AMK_Redeclaration:
2135 break;
2136
2137 case AMK_Override:
2138 Override = true;
2139 break;
2140 }
2141 }
2142
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002143 // Already handled.
2144 if (isa<UsedAttr>(*i))
2145 continue;
2146
Richard Smith671b3212013-02-22 04:55:39 +00002147 if (mergeDeclAttribute(*this, New, *i, Override))
John McCalleca5d222011-03-02 04:00:57 +00002148 foundAny = true;
Chris Lattnerddee4232008-03-03 03:28:21 +00002149 }
John McCalleca5d222011-03-02 04:00:57 +00002150
Richard Smith671b3212013-02-22 04:55:39 +00002151 if (mergeAlignedAttrs(*this, New, Old))
2152 foundAny = true;
2153
Douglas Gregor27c6da22012-01-01 20:30:41 +00002154 if (!foundAny) New->dropAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002155}
2156
2157/// mergeParamDeclAttributes - Copy attributes from the old parameter
2158/// to the new one.
2159static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2160 const ParmVarDecl *oldDecl,
Richard Smith3a2b7a12013-01-28 22:42:45 +00002161 Sema &S) {
2162 // C++11 [dcl.attr.depend]p2:
2163 // The first declaration of a function shall specify the
2164 // carries_dependency attribute for its declarator-id if any declaration
2165 // of the function specifies the carries_dependency attribute.
2166 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2167 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2168 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2169 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2170 // Find the first declaration of the parameter.
2171 // FIXME: Should we build redeclaration chains for function parameters?
2172 const FunctionDecl *FirstFD =
Rafael Espindolabc650912013-10-17 15:37:26 +00002173 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smith3a2b7a12013-01-28 22:42:45 +00002174 const ParmVarDecl *FirstVD =
2175 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2176 S.Diag(FirstVD->getLocation(),
2177 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2178 }
2179
John McCalleca5d222011-03-02 04:00:57 +00002180 if (!oldDecl->hasAttrs())
2181 return;
2182
2183 bool foundAny = newDecl->hasAttrs();
2184
2185 // Ensure that any moving of objects within the allocated map is
2186 // done before we process them.
2187 if (!foundAny) newDecl->setAttrs(AttrVec());
2188
2189 for (specific_attr_iterator<InheritableParamAttr>
2190 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2191 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2192 if (!DeclHasAttr(newDecl, *i)) {
Richard Smith3a2b7a12013-01-28 22:42:45 +00002193 InheritableAttr *newAttr =
2194 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCalleca5d222011-03-02 04:00:57 +00002195 newAttr->setInherited(true);
2196 newDecl->addAttr(newAttr);
2197 foundAny = true;
2198 }
2199 }
2200
2201 if (!foundAny) newDecl->dropAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +00002202}
2203
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002204namespace {
2205
Douglas Gregorc8376562009-03-06 22:43:54 +00002206/// Used in MergeFunctionDecl to keep track of function parameters in
2207/// C.
2208struct GNUCompatibleParamWarning {
2209 ParmVarDecl *OldParm;
2210 ParmVarDecl *NewParm;
2211 QualType PromotedType;
2212};
2213
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002214}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002215
2216/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002217Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002218 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Sean Huntf961ea52011-05-10 19:08:14 +00002219 if (Ctor->isDefaultConstructor())
2220 return Sema::CXXDefaultConstructor;
Sean Hunt9ae60d52011-05-26 01:26:05 +00002221
2222 if (Ctor->isCopyConstructor())
2223 return Sema::CXXCopyConstructor;
2224
2225 if (Ctor->isMoveConstructor())
2226 return Sema::CXXMoveConstructor;
Sean Hunt82713172011-05-25 23:16:36 +00002227 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002228 return Sema::CXXDestructor;
Sean Hunt82713172011-05-25 23:16:36 +00002229 } else if (MD->isCopyAssignmentOperator()) {
Sean Huntf961ea52011-05-10 19:08:14 +00002230 return Sema::CXXCopyAssignment;
Sebastian Redl74e611a2011-09-04 18:14:28 +00002231 } else if (MD->isMoveAssignmentOperator()) {
2232 return Sema::CXXMoveAssignment;
Sean Hunt82713172011-05-25 23:16:36 +00002233 }
Sean Huntf961ea52011-05-10 19:08:14 +00002234
Sean Huntf961ea52011-05-10 19:08:14 +00002235 return Sema::CXXInvalid;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002236}
2237
Sebastian Redl515ddd82010-06-09 21:17:41 +00002238/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002239/// only extern inline functions can be redefined, and even then only in
2240/// GNU89 mode.
2241static bool canRedefineFunction(const FunctionDecl *FD,
2242 const LangOptions& LangOpts) {
Eli Friedmaneca3ed72011-06-13 23:56:42 +00002243 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2244 !LangOpts.CPlusPlus &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002245 FD->isInlineSpecified() &&
John McCalld931b082010-08-26 03:08:43 +00002246 FD->getStorageClass() == SC_Extern);
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002247}
2248
Reid Kleckneref072032013-08-27 23:08:25 +00002249const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2250 const AttributedType *AT = T->getAs<AttributedType>();
2251 while (AT && !AT->isCallingConv())
2252 AT = AT->getModifiedType()->getAs<AttributedType>();
2253 return AT;
John McCallfb609142012-08-25 02:00:03 +00002254}
2255
Benjamin Kramera574c892013-02-15 12:30:38 +00002256template <typename T>
2257static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindola950fee22013-02-14 01:18:37 +00002258 const DeclContext *DC = Old->getDeclContext();
2259 if (DC->isRecord())
2260 return false;
2261
2262 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002263 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002264 return true;
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002265 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002266 return true;
2267 return false;
2268}
2269
Chris Lattner04421082008-04-08 04:40:51 +00002270/// MergeFunctionDecl - We just parsed a function 'New' from
2271/// declarator D which has the same name and scope as a previous
2272/// declaration 'Old'. Figure out how to resolve this situation,
2273/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002274///
2275/// In C++, New and Old must be declarations that are not
2276/// overloaded. Use IsOverload to determine whether New and Old are
2277/// overloaded, and to select the Old declaration that New should be
2278/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002279///
2280/// Returns true if there was an error, false otherwise.
Richard Smithdd9459f2013-08-13 18:18:50 +00002281bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2282 bool MergeTypeWithOld) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002283 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002284 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002285 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00002286 = dyn_cast<FunctionTemplateDecl>(OldD))
2287 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002288 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002289 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00002291 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCall78037ac2013-04-03 21:19:47 +00002292 if (New->getFriendObjectKind()) {
2293 Diag(New->getLocation(), diag::err_using_decl_friend);
2294 Diag(Shadow->getTargetDecl()->getLocation(),
2295 diag::note_using_decl_target);
2296 Diag(Shadow->getUsingDecl()->getLocation(),
2297 diag::note_using_decl) << 0;
2298 return true;
2299 }
2300
John McCall41ce66f2009-12-10 19:51:03 +00002301 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2302 Diag(Shadow->getTargetDecl()->getLocation(),
2303 diag::note_using_decl_target);
2304 Diag(Shadow->getUsingDecl()->getLocation(),
2305 diag::note_using_decl) << 0;
2306 return true;
2307 }
2308
Chris Lattner5dc266a2008-11-20 06:13:02 +00002309 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002310 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002311 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00002312 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002314
David Majnemerbcd06502013-07-07 23:49:50 +00002315 // If the old declaration is invalid, just give up here.
2316 if (Old->isInvalidDecl())
2317 return true;
2318
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002319 // Determine whether the previous declaration was a definition,
2320 // implicit declaration, or a declaration.
2321 diag::kind PrevDiag;
2322 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00002323 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002324 else if (Old->isImplicit())
2325 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002326 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00002327 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002329 // Don't complain about this if we're in GNU89 mode and the old function
2330 // is an extern inline function.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002331 // Don't complain about specializations. They are not supposed to have
2332 // storage classes.
Douglas Gregor04495c82009-02-24 01:23:02 +00002333 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCalld931b082010-08-26 03:08:43 +00002334 New->getStorageClass() == SC_Static &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00002335 Old->hasExternalFormalLinkage() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002336 !New->getTemplateSpecializationInfo() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002337 !canRedefineFunction(Old, getLangOpts())) {
2338 if (getLangOpts().MicrosoftExt) {
Francois Pichet4bada2e2011-04-22 19:50:06 +00002339 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2340 Diag(Old->getLocation(), PrevDiag);
2341 } else {
2342 Diag(New->getLocation(), diag::err_static_non_static) << New;
2343 Diag(Old->getLocation(), PrevDiag);
2344 return true;
2345 }
Douglas Gregor04495c82009-02-24 01:23:02 +00002346 }
2347
Reid Kleckneref072032013-08-27 23:08:25 +00002348
2349 // If a function is first declared with a calling convention, but is later
2350 // declared or defined without one, all following decls assume the calling
2351 // convention of the first.
John McCallf82b4e82010-02-04 05:44:44 +00002352 //
John McCallfb609142012-08-25 02:00:03 +00002353 // It's OK if a function is first declared without a calling convention,
2354 // but is later declared or defined with the default calling convention.
2355 //
Reid Kleckneref072032013-08-27 23:08:25 +00002356 // To test if either decl has an explicit calling convention, we look for
2357 // AttributedType sugar nodes on the type as written. If they are missing or
2358 // were canonicalized away, we assume the calling convention was implicit.
John McCallf82b4e82010-02-04 05:44:44 +00002359 //
2360 // Note also that we DO NOT return at this point, because we still have
2361 // other tests to run.
Reid Kleckneref072032013-08-27 23:08:25 +00002362 QualType OldQType = Context.getCanonicalType(Old->getType());
2363 QualType NewQType = Context.getCanonicalType(New->getType());
John McCalle6a365d2010-12-19 02:44:49 +00002364 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckneref072032013-08-27 23:08:25 +00002365 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCalle6a365d2010-12-19 02:44:49 +00002366 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2367 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2368 bool RequiresAdjustment = false;
John McCallfb609142012-08-25 02:00:03 +00002369
Reid Kleckneref072032013-08-27 23:08:25 +00002370 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindolabc650912013-10-17 15:37:26 +00002371 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckneref072032013-08-27 23:08:25 +00002372 const FunctionType *FT =
2373 First->getType().getCanonicalType()->castAs<FunctionType>();
2374 FunctionType::ExtInfo FI = FT->getExtInfo();
2375 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2376 if (!NewCCExplicit) {
2377 // Inherit the CC from the previous declaration if it was specified
2378 // there but not here.
2379 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2380 RequiresAdjustment = true;
2381 } else {
2382 // Calling conventions aren't compatible, so complain.
2383 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2384 Diag(New->getLocation(), diag::err_cconv_change)
2385 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2386 << !FirstCCExplicit
2387 << (!FirstCCExplicit ? "" :
2388 FunctionType::getNameForCallConv(FI.getCC()));
John McCallfb609142012-08-25 02:00:03 +00002389
Reid Kleckneref072032013-08-27 23:08:25 +00002390 // Put the note on the first decl, since it is the one that matters.
2391 Diag(First->getLocation(), diag::note_previous_declaration);
2392 return true;
2393 }
John McCallf82b4e82010-02-04 05:44:44 +00002394 }
2395
John McCall04a67a62010-02-05 21:31:56 +00002396 // FIXME: diagnose the other way around?
John McCalle6a365d2010-12-19 02:44:49 +00002397 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2398 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2399 RequiresAdjustment = true;
John McCall04a67a62010-02-05 21:31:56 +00002400 }
2401
Douglas Gregord2c64902010-06-18 21:30:25 +00002402 // Merge regparm attribute.
Eli Friedmana49218e2011-04-09 08:18:08 +00002403 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2404 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2405 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregord2c64902010-06-18 21:30:25 +00002406 Diag(New->getLocation(), diag::err_regparm_mismatch)
2407 << NewType->getRegParmType()
2408 << OldType->getRegParmType();
2409 Diag(Old->getLocation(), diag::note_previous_declaration);
2410 return true;
2411 }
John McCalle6a365d2010-12-19 02:44:49 +00002412
2413 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2414 RequiresAdjustment = true;
2415 }
2416
Douglas Gregorcb1c9c32011-10-14 15:55:40 +00002417 // Merge ns_returns_retained attribute.
2418 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2419 if (NewTypeInfo.getProducesResult()) {
2420 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2421 Diag(Old->getLocation(), diag::note_previous_declaration);
2422 return true;
2423 }
2424
2425 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2426 RequiresAdjustment = true;
2427 }
2428
John McCalle6a365d2010-12-19 02:44:49 +00002429 if (RequiresAdjustment) {
Eli Friedman130fcc82013-09-06 21:09:09 +00002430 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2431 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2432 New->setType(QualType(AdjustedType, 0));
John McCalle6a365d2010-12-19 02:44:49 +00002433 NewQType = Context.getCanonicalType(New->getType());
Eli Friedman130fcc82013-09-06 21:09:09 +00002434 NewType = cast<FunctionType>(NewQType);
Douglas Gregord2c64902010-06-18 21:30:25 +00002435 }
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002436
2437 // If this redeclaration makes the function inline, we may need to add it to
2438 // UndefinedButUsed.
2439 if (!Old->isInlined() && New->isInlined() &&
2440 !New->hasAttr<GNUInlineAttr>() &&
2441 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2442 Old->isUsed(false) &&
2443 !Old->isDefined() && !New->isThisDeclarationADefinition())
2444 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2445 SourceLocation()));
2446
2447 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2448 // about it.
2449 if (New->hasAttr<GNUInlineAttr>() &&
2450 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2451 UndefinedButUsed.erase(Old->getCanonicalDecl());
2452 }
Douglas Gregord2c64902010-06-18 21:30:25 +00002453
David Blaikie4e4d0842012-03-11 07:00:24 +00002454 if (getLangOpts().CPlusPlus) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002455 // (C++98 13.1p2):
2456 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00002457 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002458 // cannot be overloaded.
Richard Smith60e141e2013-05-04 07:00:32 +00002459
2460 // Go back to the type source info to compare the declared return types,
Richard Smith37e849a2013-08-14 20:16:31 +00002461 // per C++1y [dcl.type.auto]p13:
Richard Smith60e141e2013-05-04 07:00:32 +00002462 // Redeclarations or specializations of a function or function template
2463 // with a declared return type that uses a placeholder type shall also
2464 // use that placeholder, not a deduced type.
2465 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2466 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2467 : OldType)->getResultType();
2468 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2469 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2470 : NewType)->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002471 QualType ResQT;
Richard Smitha41c97a2013-09-20 01:15:31 +00002472 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2473 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2474 New->isLocalExternDecl())) {
Richard Smith60e141e2013-05-04 07:00:32 +00002475 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2476 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002477 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2478 if (ResQT.isNull()) {
Argyrios Kyrtzidis1de34dd2011-02-05 05:54:49 +00002479 if (New->isCXXClassMember() && New->isOutOfLine())
2480 Diag(New->getLocation(),
2481 diag::err_member_def_does_not_match_ret_type) << New;
2482 else
2483 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002484 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2485 return true;
2486 }
2487 else
2488 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002489 }
2490
Richard Smith60e141e2013-05-04 07:00:32 +00002491 QualType OldReturnType = OldType->getResultType();
2492 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2493 if (OldReturnType != NewReturnType) {
2494 // If this function has a deduced return type and has already been
2495 // defined, copy the deduced value from the old declaration.
2496 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2497 if (OldAT && OldAT->isDeduced()) {
Richard Smith37e849a2013-08-14 20:16:31 +00002498 New->setType(
2499 SubstAutoType(New->getType(),
2500 OldAT->isDependentType() ? Context.DependentTy
2501 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002502 NewQType = Context.getCanonicalType(
Richard Smith37e849a2013-08-14 20:16:31 +00002503 SubstAutoType(NewQType,
2504 OldAT->isDependentType() ? Context.DependentTy
2505 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002506 }
2507 }
2508
2509 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2510 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002511 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00002512 // Preserve triviality.
2513 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichete1e96a62011-05-14 19:17:07 +00002514
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002515 // MSVC allows explicit template specialization at class scope:
2516 // 2 CXMethodDecls referring to the same function will be injected.
2517 // We don't want a redeclartion error.
2518 bool IsClassScopeExplicitSpecialization =
2519 OldMethod->isFunctionTemplateSpecialization() &&
2520 NewMethod->isFunctionTemplateSpecialization();
John McCall3d043362010-04-13 07:45:41 +00002521 bool isFriend = NewMethod->getFriendObjectKind();
2522
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002523 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2524 !IsClassScopeExplicitSpecialization) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002525 // -- Member function declarations with the same name and the
2526 // same parameter types cannot be overloaded if any of them
2527 // is a static member function declaration.
Eli Friedmanfa0d3f82013-06-19 22:43:55 +00002528 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002529 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2530 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2531 return true;
2532 }
Richard Smith838925d2012-07-13 04:12:04 +00002533
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002534 // C++ [class.mem]p1:
2535 // [...] A member shall not be declared twice in the
2536 // member-specification, except that a nested class or member
2537 // class template can be declared and then later defined.
Richard Smith838925d2012-07-13 04:12:04 +00002538 if (ActiveTemplateInstantiations.empty()) {
2539 unsigned NewDiag;
2540 if (isa<CXXConstructorDecl>(OldMethod))
2541 NewDiag = diag::err_constructor_redeclared;
2542 else if (isa<CXXDestructorDecl>(NewMethod))
2543 NewDiag = diag::err_destructor_redeclared;
2544 else if (isa<CXXConversionDecl>(NewMethod))
2545 NewDiag = diag::err_conv_function_redeclared;
2546 else
2547 NewDiag = diag::err_member_redeclared;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002548
Richard Smith838925d2012-07-13 04:12:04 +00002549 Diag(New->getLocation(), NewDiag);
2550 } else {
2551 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2552 << New << New->getType();
2553 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00002554 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00002555
2556 // Complain if this is an explicit declaration of a special
2557 // member that was initially declared implicitly.
2558 //
2559 // As an exception, it's okay to befriend such methods in order
2560 // to permit the implicit constructor/destructor/operator calls.
2561 } else if (OldMethod->isImplicit()) {
2562 if (isFriend) {
2563 NewMethod->setImplicit();
2564 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002565 Diag(NewMethod->getLocation(),
2566 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002567 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002568 return true;
2569 }
Richard Smithf4fe8432012-06-08 01:30:54 +00002570 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Sean Hunt001cad92011-05-10 00:49:42 +00002571 Diag(NewMethod->getLocation(),
2572 diag::err_definition_of_explicitly_defaulted_member)
2573 << getSpecialMember(OldMethod);
2574 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002575 }
2576 }
2577
Richard Smithcd8ab512013-01-17 01:30:42 +00002578 // C++11 [dcl.attr.noreturn]p1:
2579 // The first declaration of a function shall specify the noreturn
2580 // attribute if any declaration of that function specifies the noreturn
2581 // attribute.
2582 if (New->hasAttr<CXX11NoReturnAttr>() &&
2583 !Old->hasAttr<CXX11NoReturnAttr>()) {
2584 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2585 diag::err_noreturn_missing_on_first_decl);
Rafael Espindolabc650912013-10-17 15:37:26 +00002586 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithcd8ab512013-01-17 01:30:42 +00002587 diag::note_noreturn_missing_first_decl);
2588 }
2589
Richard Smith3a2b7a12013-01-28 22:42:45 +00002590 // C++11 [dcl.attr.depend]p2:
2591 // The first declaration of a function shall specify the
2592 // carries_dependency attribute for its declarator-id if any declaration
2593 // of the function specifies the carries_dependency attribute.
2594 if (New->hasAttr<CarriesDependencyAttr>() &&
2595 !Old->hasAttr<CarriesDependencyAttr>()) {
2596 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2597 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindolabc650912013-10-17 15:37:26 +00002598 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002599 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2600 }
2601
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002602 // (C++98 8.3.5p3):
2603 // All declarations for a function shall agree exactly in both the
2604 // return type and the parameter-type-list.
John McCalle6a365d2010-12-19 02:44:49 +00002605 // We also want to respect all the extended bits except noreturn.
2606
2607 // noreturn should now match unless the old type info didn't have it.
2608 QualType OldQTypeForComparison = OldQType;
2609 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2610 assert(OldQType == QualType(OldType, 0));
2611 const FunctionType *OldTypeForComparison
2612 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2613 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2614 assert(OldQTypeForComparison.isCanonical());
2615 }
2616
Rafael Espindola950fee22013-02-14 01:18:37 +00002617 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokera8a2ebe2013-10-22 22:53:01 +00002618 // As a special case, retain the language linkage from previous
2619 // declarations of a friend function as an extension.
2620 //
2621 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2622 // and is useful because there's otherwise no way to specify language
2623 // linkage within class scope.
2624 //
2625 // Check cautiously as the friend object kind isn't yet complete.
2626 if (New->getFriendObjectKind() != Decl::FOK_None) {
2627 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2628 Diag(Old->getLocation(), PrevDiag);
2629 } else {
2630 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2631 Diag(Old->getLocation(), PrevDiag);
2632 return true;
2633 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00002634 }
2635
John McCalle6a365d2010-12-19 02:44:49 +00002636 if (OldQTypeForComparison == NewQType)
Richard Smithdd9459f2013-08-13 18:18:50 +00002637 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002638
Richard Smitha41c97a2013-09-20 01:15:31 +00002639 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2640 New->isLocalExternDecl()) {
2641 // It's OK if we couldn't merge types for a local function declaraton
2642 // if either the old or new type is dependent. We'll merge the types
2643 // when we instantiate the function.
2644 return false;
2645 }
2646
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002647 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00002648 }
Chris Lattner04421082008-04-08 04:40:51 +00002649
2650 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002651 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002652 if (!getLangOpts().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00002653 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00002654 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2655 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002656 const FunctionProtoType *OldProto = 0;
Richard Smithdd9459f2013-08-13 18:18:50 +00002657 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002658 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00002659 // The old declaration provided a function prototype, but the
2660 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00002661 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002662 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregor68719812009-02-16 18:20:44 +00002663 OldProto->arg_type_end());
2664 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002665 ParamTypes,
John McCalle23cf432010-12-14 08:05:40 +00002666 OldProto->getExtProtoInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00002667 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00002668 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00002669
2670 // Synthesize a parameter for each argument type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002671 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00002672 for (FunctionProtoType::arg_type_iterator
2673 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00002674 ParamEnd = OldProto->arg_type_end();
2675 ParamType != ParamEnd; ++ParamType) {
2676 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002677 SourceLocation(),
Douglas Gregor450da982009-02-16 20:58:07 +00002678 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002679 *ParamType, /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002680 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002681 0);
John McCallfb44de92011-05-01 22:35:37 +00002682 Param->setScopeInfo(0, Params.size());
Douglas Gregor450da982009-02-16 20:58:07 +00002683 Param->setImplicit();
2684 Params.push_back(Param);
2685 }
2686
David Blaikie4278c652011-09-21 18:16:56 +00002687 New->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00002688 }
Douglas Gregor68719812009-02-16 18:20:44 +00002689
Richard Smithdd9459f2013-08-13 18:18:50 +00002690 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattner04421082008-04-08 04:40:51 +00002691 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00002692
Douglas Gregorc8376562009-03-06 22:43:54 +00002693 // GNU C permits a K&R definition to follow a prototype declaration
2694 // if the declared types of the parameters in the K&R definition
2695 // match the types in the prototype declaration, even when the
2696 // promoted types of the parameters from the K&R definition differ
2697 // from the types in the prototype. GCC then keeps the types from
2698 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002699 //
2700 // If a variadic prototype is followed by a non-variadic K&R definition,
2701 // the K&R definition becomes variadic. This is sort of an edge case, but
2702 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2703 // C99 6.9.1p8.
David Blaikie4e4d0842012-03-11 07:00:24 +00002704 if (!getLangOpts().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002705 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00002706 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002707 Old->getNumParams() == New->getNumParams()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002708 SmallVector<QualType, 16> ArgTypes;
2709 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00002710 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00002711 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002712 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00002713 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002714
Douglas Gregorc8376562009-03-06 22:43:54 +00002715 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002716 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2717 NewProto->getResultType());
2718 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00002719 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002720 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002721 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2722 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00002723 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00002724 NewProto->getArgType(Idx))) {
2725 ArgTypes.push_back(NewParm->getType());
2726 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00002727 NewParm->getType(),
2728 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002729 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00002730 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2731 Warnings.push_back(Warn);
2732 ArgTypes.push_back(NewParm->getType());
2733 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002734 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00002735 }
2736
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002737 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002738 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2739 Diag(Warnings[Warn].NewParm->getLocation(),
2740 diag::ext_param_promoted_not_compatible_with_prototype)
2741 << Warnings[Warn].PromotedType
2742 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00002743 if (Warnings[Warn].OldParm->getLocation().isValid())
2744 Diag(Warnings[Warn].OldParm->getLocation(),
2745 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00002746 }
2747
Richard Smithdd9459f2013-08-13 18:18:50 +00002748 if (MergeTypeWithOld)
2749 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2750 OldProto->getExtProtoInfo()));
2751 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregorc8376562009-03-06 22:43:54 +00002752 }
2753
2754 // Fall through to diagnose conflicting types.
2755 }
2756
John McCall088831d2013-04-14 08:50:55 +00002757 // A function that has already been declared has been redeclared or
2758 // defined with a different type; show an appropriate diagnostic.
2759
2760 // If the previous declaration was an implicitly-generated builtin
2761 // declaration, then at the very least we should use a specialized note.
2762 unsigned BuiltinID;
2763 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2764 // If it's actually a library-defined builtin function like 'malloc'
2765 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002766 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002767 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2768 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2769 << Old << Old->getType();
John McCall088831d2013-04-14 08:50:55 +00002770
2771 // If this is a global redeclaration, just forget hereafter
2772 // about the "builtin-ness" of the function.
2773 //
2774 // Doing this for local extern declarations is problematic. If
2775 // the builtin declaration remains visible, a second invalid
2776 // local declaration will produce a hard error; if it doesn't
2777 // remain visible, a single bogus local redeclaration (which is
2778 // actually only a warning) could break all the downstream code.
Richard Smitha41c97a2013-09-20 01:15:31 +00002779 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCall088831d2013-04-14 08:50:55 +00002780 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2781
Douglas Gregor374e1562009-03-23 17:47:24 +00002782 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002783 }
Steve Naroff837618c2008-01-16 15:01:34 +00002784
Douglas Gregorcda9c672009-02-16 17:45:42 +00002785 PrevDiag = diag::note_previous_builtin_declaration;
2786 }
2787
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002788 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00002789 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00002790 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002791}
2792
Douglas Gregor04495c82009-02-24 01:23:02 +00002793/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00002794/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00002795///
2796/// This routine handles the merging of attributes and other
Alp Toker89673e02013-10-22 09:00:49 +00002797/// properties of function declarations from the old declaration to
Douglas Gregor04495c82009-02-24 01:23:02 +00002798/// the new declaration, once we know that New is in fact a
2799/// redeclaration of Old.
2800///
2801/// \returns false
James Molloy9cda03f2012-03-13 08:55:35 +00002802bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smithdd9459f2013-08-13 18:18:50 +00002803 Scope *S, bool MergeTypeWithOld) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002804 // Merge the attributes
Douglas Gregor27c6da22012-01-01 20:30:41 +00002805 mergeDeclAttributes(New, Old);
Douglas Gregor04495c82009-02-24 01:23:02 +00002806
Douglas Gregor04495c82009-02-24 01:23:02 +00002807 // Merge "pure" flag.
2808 if (Old->isPure())
2809 New->setPure();
2810
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002811 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00002812 if (Old->getMostRecentDecl()->isUsed(false))
2813 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002814
John McCalleca5d222011-03-02 04:00:57 +00002815 // Merge attributes from the parameters. These can mismatch with K&R
2816 // declarations.
2817 if (New->getNumParams() == Old->getNumParams())
2818 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2819 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002820 *this);
John McCalleca5d222011-03-02 04:00:57 +00002821
David Blaikie4e4d0842012-03-11 07:00:24 +00002822 if (getLangOpts().CPlusPlus)
James Molloy9cda03f2012-03-13 08:55:35 +00002823 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregor04495c82009-02-24 01:23:02 +00002824
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002825 // Merge the function types so the we get the composite types for the return
Richard Smithdd9459f2013-08-13 18:18:50 +00002826 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2827 // was visible.
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002828 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smithdd9459f2013-08-13 18:18:50 +00002829 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002830 New->setType(Merged);
2831
Douglas Gregor04495c82009-02-24 01:23:02 +00002832 return false;
2833}
2834
John McCallf85e1932011-06-15 23:02:42 +00002835
John McCalleca5d222011-03-02 04:00:57 +00002836void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002837 ObjCMethodDecl *oldMethod) {
John McCall6c2c2502011-07-22 02:45:48 +00002838
Fariborz Jahanian1ea67442012-06-05 21:14:46 +00002839 // Merge the attributes, including deprecated/unavailable
Ted Kremenekcb344392013-04-06 00:34:27 +00002840 AvailabilityMergeKind MergeKind =
2841 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2842 : AMK_Override;
2843 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCalleca5d222011-03-02 04:00:57 +00002844
2845 // Merge attributes from the parameters.
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002846 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2847 oe = oldMethod->param_end();
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002848 for (ObjCMethodDecl::param_iterator
John McCalleca5d222011-03-02 04:00:57 +00002849 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002850 ni != ne && oi != oe; ++ni, ++oi)
Richard Smith3a2b7a12013-01-28 22:42:45 +00002851 mergeParamDeclAttributes(*ni, *oi, *this);
John McCall6c2c2502011-07-22 02:45:48 +00002852
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002853 CheckObjCMethodOverride(newMethod, oldMethod);
John McCalleca5d222011-03-02 04:00:57 +00002854}
2855
Sebastian Redl60618fa2011-03-12 11:50:43 +00002856/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2857/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith34b41d92011-02-20 03:19:35 +00002858/// emitting diagnostics as appropriate.
2859///
2860/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002861/// to here in AddInitializerToDecl. We can't check them before the initializer
2862/// is attached.
Richard Smithdd9459f2013-08-13 18:18:50 +00002863void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2864 bool MergeTypeWithOld) {
Richard Smith34b41d92011-02-20 03:19:35 +00002865 if (New->isInvalidDecl() || Old->isInvalidDecl())
2866 return;
2867
2868 QualType MergedT;
David Blaikie4e4d0842012-03-11 07:00:24 +00002869 if (getLangOpts().CPlusPlus) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00002870 if (New->getType()->isUndeducedType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00002871 // We don't know what the new type is until the initializer is attached.
2872 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002873 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2874 // These could still be something that needs exception specs checked.
2875 return MergeVarDeclExceptionSpecs(New, Old);
2876 }
Richard Smith34b41d92011-02-20 03:19:35 +00002877 // C++ [basic.link]p10:
2878 // [...] the types specified by all declarations referring to a given
2879 // object or function shall be identical, except that declarations for an
2880 // array object can specify array types that differ by the presence or
2881 // absence of a major array bound (8.3.4).
2882 else if (Old->getType()->isIncompleteArrayType() &&
2883 New->getType()->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002884 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2885 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2886 if (Context.hasSameType(OldArray->getElementType(),
2887 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002888 MergedT = New->getType();
2889 } else if (Old->getType()->isArrayType() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00002890 New->getType()->isIncompleteArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002891 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2892 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2893 if (Context.hasSameType(OldArray->getElementType(),
2894 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002895 MergedT = Old->getType();
Richard Smitha41c97a2013-09-20 01:15:31 +00002896 } else if (New->getType()->isObjCObjectPointerType() &&
2897 Old->getType()->isObjCObjectPointerType()) {
2898 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2899 Old->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00002900 }
2901 } else {
Richard Smitha41c97a2013-09-20 01:15:31 +00002902 // C 6.2.7p2:
2903 // All declarations that refer to the same object or function shall have
2904 // compatible type.
Richard Smith34b41d92011-02-20 03:19:35 +00002905 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2906 }
2907 if (MergedT.isNull()) {
Richard Smithdd9459f2013-08-13 18:18:50 +00002908 // It's OK if we couldn't merge types if either type is dependent, for a
2909 // block-scope variable. In other cases (static data members of class
2910 // templates, variable templates, ...), we require the types to be
2911 // equivalent.
2912 // FIXME: The C++ standard doesn't say anything about this.
2913 if ((New->getType()->isDependentType() ||
2914 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2915 // If the old type was dependent, we can't merge with it, so the new type
2916 // becomes dependent for now. We'll reproduce the original type when we
2917 // instantiate the TypeSourceInfo for the variable.
2918 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2919 New->setType(Context.DependentTy);
2920 return;
2921 }
2922
2923 // FIXME: Even if this merging succeeds, some other non-visible declaration
2924 // of this variable might have an incompatible type. For instance:
2925 //
2926 // extern int arr[];
2927 // void f() { extern int arr[2]; }
2928 // void g() { extern int arr[3]; }
2929 //
2930 // Neither C nor C++ requires a diagnostic for this, but we should still try
2931 // to diagnose it.
Richard Smith34b41d92011-02-20 03:19:35 +00002932 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikiea405b252012-09-20 18:38:57 +00002933 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00002934 Diag(Old->getLocation(), diag::note_previous_definition);
2935 return New->setInvalidDecl();
2936 }
John McCall5b8740f2013-04-01 18:34:28 +00002937
2938 // Don't actually update the type on the new declaration if the old
Richard Smith99a72382013-09-03 21:00:58 +00002939 // declaration was an extern declaration in a different scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00002940 if (MergeTypeWithOld)
John McCall5b8740f2013-04-01 18:34:28 +00002941 New->setType(MergedT);
Richard Smith34b41d92011-02-20 03:19:35 +00002942}
2943
Richard Smith99a72382013-09-03 21:00:58 +00002944static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2945 LookupResult &Previous) {
2946 // C11 6.2.7p4:
2947 // For an identifier with internal or external linkage declared
2948 // in a scope in which a prior declaration of that identifier is
2949 // visible, if the prior declaration specifies internal or
2950 // external linkage, the type of the identifier at the later
2951 // declaration becomes the composite type.
2952 //
2953 // If the variable isn't visible, we do not merge with its type.
2954 if (Previous.isShadowed())
2955 return false;
2956
2957 if (S.getLangOpts().CPlusPlus) {
2958 // C++11 [dcl.array]p3:
2959 // If there is a preceding declaration of the entity in the same
2960 // scope in which the bound was specified, an omitted array bound
2961 // is taken to be the same as in that earlier declaration.
2962 return NewVD->isPreviousDeclInSameBlockScope() ||
2963 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2964 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2965 } else {
2966 // If the old declaration was function-local, don't merge with its
2967 // type unless we're in the same function.
2968 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2969 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2970 }
2971}
2972
Reid Spencer5f016e22007-07-11 17:01:13 +00002973/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2974/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2975/// situation, merging decls or emitting diagnostics as appropriate.
2976///
Mike Stump1eb44332009-09-09 15:08:12 +00002977/// Tentative definition rules (C99 6.9.2p2) are checked by
2978/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002979/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00002980///
Richard Smith99a72382013-09-03 21:00:58 +00002981void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall68263142009-11-18 22:49:29 +00002982 // If the new decl is already invalid, don't do any other checking.
2983 if (New->isInvalidDecl())
2984 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Larisse Voufo4a919892013-08-14 03:09:19 +00002986 // Verify the old decl was also a variable or variable template.
John McCall68263142009-11-18 22:49:29 +00002987 VarDecl *Old = 0;
Larisse Voufo4a919892013-08-14 03:09:19 +00002988 if (Previous.isSingleResult() &&
2989 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo567f9172013-08-22 00:59:14 +00002990 if (New->getDescribedVarTemplate())
Larisse Voufo4a919892013-08-14 03:09:19 +00002991 Old = Old->getDescribedVarTemplate() ? Old : 0;
2992 else
2993 Old = Old->getDescribedVarTemplate() ? 0 : Old;
2994 }
2995 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002996 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002997 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00002998 Diag(Previous.getRepresentativeDecl()->getLocation(),
2999 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003000 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003001 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003002
Rafael Espindola90cc3902013-04-15 12:49:13 +00003003 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3004 return;
3005
Douglas Gregor7f6ff022010-08-30 14:32:14 +00003006 // C++ [class.mem]p1:
3007 // A member shall not be declared twice in the member-specification [...]
3008 //
3009 // Here, we need only consider static data members.
3010 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3011 Diag(New->getLocation(), diag::err_duplicate_member)
3012 << New->getIdentifier();
3013 Diag(Old->getLocation(), diag::note_previous_declaration);
3014 New->setInvalidDecl();
3015 }
3016
Douglas Gregor27c6da22012-01-01 20:30:41 +00003017 mergeDeclAttributes(New, Old);
David Blaikied662a792011-10-19 22:56:21 +00003018 // Warn if an already-declared variable is made a weak_import in a subsequent
3019 // declaration
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00003020 if (New->getAttr<WeakImportAttr>() &&
3021 Old->getStorageClass() == SC_None &&
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003022 !Old->getAttr<WeakImportAttr>()) {
3023 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3024 Diag(Old->getLocation(), diag::note_previous_definition);
3025 // Remove weak_import attribute on new declaration.
Fariborz Jahanianc3ca14d2011-06-23 17:50:10 +00003026 New->dropAttr<WeakImportAttr>();
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003027 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003028
Richard Smith34b41d92011-02-20 03:19:35 +00003029 // Merge the types.
Richard Smith99a72382013-09-03 21:00:58 +00003030 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3031
Richard Smith34b41d92011-02-20 03:19:35 +00003032 if (New->isInvalidDecl())
3033 return;
Douglas Gregor656de632009-03-11 23:52:16 +00003034
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003035 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCalld931b082010-08-26 03:08:43 +00003036 if (New->getStorageClass() == SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003037 !New->isStaticDataMember() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00003038 Old->hasExternalFormalLinkage()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003039 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003040 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003041 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003042 }
Mike Stump1eb44332009-09-09 15:08:12 +00003043 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003044 // For an identifier declared with the storage-class specifier
3045 // extern in a scope in which a prior declaration of that
3046 // identifier is visible,23) if the prior declaration specifies
3047 // internal or external linkage, the linkage of the identifier at
3048 // the later declaration is the same as the linkage specified at
3049 // the prior declaration. If no prior declaration is visible, or
3050 // if the prior declaration specifies no linkage, then the
3051 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00003052 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003053 /* Okay */;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003054 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003055 !New->isStaticDataMember() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003056 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003057 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003058 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003059 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003060 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003061
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003062 // Check if extern is followed by non-extern and vice-versa.
3063 if (New->hasExternalStorage() &&
3064 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3065 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3066 Diag(Old->getLocation(), diag::note_previous_definition);
3067 return New->setInvalidDecl();
3068 }
Rafael Espindola80a86892013-04-04 02:47:57 +00003069 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3070 !New->hasExternalStorage()) {
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003071 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3072 Diag(Old->getLocation(), diag::note_previous_definition);
3073 return New->setInvalidDecl();
3074 }
3075
Steve Naroff094cefb2008-09-17 14:05:40 +00003076 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003078 // FIXME: The test for external storage here seems wrong? We still
3079 // need to check for mismatches.
3080 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00003081 // Don't complain about out-of-line definitions of static members.
3082 !(Old->getLexicalDeclContext()->isRecord() &&
3083 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00003084 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003085 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003086 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003087 }
Douglas Gregor275a3692009-03-10 23:43:53 +00003088
Richard Smith38afbc72013-04-13 02:43:54 +00003089 if (New->getTLSKind() != Old->getTLSKind()) {
3090 if (!Old->getTLSKind()) {
3091 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3092 Diag(Old->getLocation(), diag::note_previous_declaration);
3093 } else if (!New->getTLSKind()) {
3094 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3095 Diag(Old->getLocation(), diag::note_previous_declaration);
3096 } else {
3097 // Do not allow redeclaration to change the variable between requiring
3098 // static and dynamic initialization.
3099 // FIXME: GCC allows this, but uses the TLS keyword on the first
3100 // declaration to determine the kind. Do we need to be compatible here?
3101 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3102 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3103 Diag(Old->getLocation(), diag::note_previous_declaration);
3104 }
Eli Friedman63054b32009-04-19 20:27:55 +00003105 }
3106
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003107 // C++ doesn't have tentative definitions, so go right ahead and check here.
3108 const VarDecl *Def;
David Blaikie4e4d0842012-03-11 07:00:24 +00003109 if (getLangOpts().CPlusPlus &&
Sebastian Redl6c048a92010-02-03 02:08:48 +00003110 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003111 (Def = Old->getDefinition())) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003112 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003113 Diag(Def->getLocation(), diag::note_previous_definition);
3114 New->setInvalidDecl();
3115 return;
3116 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003117
Rafael Espindola950fee22013-02-14 01:18:37 +00003118 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003119 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3120 Diag(Old->getLocation(), diag::note_previous_definition);
3121 New->setInvalidDecl();
3122 return;
3123 }
3124
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003125 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00003126 if (Old->getMostRecentDecl()->isUsed(false))
3127 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003128
Douglas Gregor275a3692009-03-10 23:43:53 +00003129 // Keep a chain of previous declarations.
Rafael Espindolabc650912013-10-17 15:37:26 +00003130 New->setPreviousDecl(Old);
John McCall46460a62010-01-20 21:53:11 +00003131
3132 // Inherit access appropriately.
3133 New->setAccess(Old->getAccess());
Larisse Voufo567f9172013-08-22 00:59:14 +00003134
3135 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3136 if (New->isStaticDataMember() && New->isOutOfLine())
3137 VTD->setAccess(New->getAccess());
3138 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003139}
3140
3141/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3142/// no declarator (e.g. "struct foo;") is parsed.
John McCalld226f652010-08-21 09:40:31 +00003143Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallac4df242011-03-22 23:00:04 +00003144 DeclSpec &DS) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00003145 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth0f4be742011-05-03 18:35:10 +00003146}
3147
Eli Friedman5e867c82013-07-10 00:30:46 +00003148static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00003149 if (!S.Context.getLangOpts().CPlusPlus)
3150 return;
3151
Eli Friedman5e867c82013-07-10 00:30:46 +00003152 if (isa<CXXRecordDecl>(Tag->getParent())) {
3153 // If this tag is the direct child of a class, number it if
3154 // it is anonymous.
3155 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3156 return;
3157 MangleNumberingContext &MCtx =
3158 S.Context.getManglingNumberContext(Tag->getParent());
3159 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3160 return;
3161 }
3162
3163 // If this tag isn't a direct child of a class, number it if it is local.
3164 Decl *ManglingContextDecl;
3165 if (MangleNumberingContext *MCtx =
3166 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3167 ManglingContextDecl)) {
3168 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3169 }
3170}
3171
Chandler Carruth0f4be742011-05-03 18:35:10 +00003172/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithc7f81162013-03-18 22:52:47 +00003173/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth0f4be742011-05-03 18:35:10 +00003174/// parameters to cope with template friend declarations.
3175Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3176 DeclSpec &DS,
Richard Smithc7f81162013-03-18 22:52:47 +00003177 MultiTemplateParamsArg TemplateParams,
3178 bool IsExplicitInstantiation) {
John McCalle3af0232009-10-07 23:34:25 +00003179 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003180 TagDecl *Tag = 0;
3181 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3182 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003183 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003184 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003185 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallb3d87482010-08-24 05:47:05 +00003186 TagD = DS.getRepAsDecl();
John McCalle3af0232009-10-07 23:34:25 +00003187
3188 if (!TagD) // We probably had an error
John McCalld226f652010-08-21 09:40:31 +00003189 return 0;
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003190
John McCall67d1a672009-08-06 02:15:43 +00003191 // Note that the above type specs guarantee that the
3192 // type rep is a Decl, whereas in many of the others
3193 // it's a Type.
Peter Collingbourne0661bd0c2011-10-23 17:07:16 +00003194 if (isa<TagDecl>(TagD))
3195 Tag = cast<TagDecl>(TagD);
3196 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3197 Tag = CTD->getTemplatedDecl();
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003198 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003199
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003200 if (Tag) {
Eli Friedman5e867c82013-07-10 00:30:46 +00003201 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003202 Tag->setFreeStanding();
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003203 if (Tag->isInvalidDecl())
3204 return Tag;
3205 }
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003206
Nuno Lopes0a8bab02009-12-17 11:35:26 +00003207 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3208 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3209 // or incomplete types shall not be restrict-qualified."
3210 if (TypeQuals & DeclSpec::TQ_restrict)
3211 Diag(DS.getRestrictSpecLoc(),
3212 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3213 << DS.getSourceRange();
3214 }
3215
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003216 if (DS.isConstexprSpecified()) {
3217 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3218 // and definitions of functions and variables.
3219 if (Tag)
3220 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3221 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3222 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003223 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3224 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003225 else
3226 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3227 // Don't emit warnings after this error.
3228 return TagD;
3229 }
3230
Richard Smithc7f81162013-03-18 22:52:47 +00003231 DiagnoseFunctionSpecifiers(DS);
3232
Douglas Gregord85bea22009-09-26 06:47:28 +00003233 if (DS.isFriendSpecified()) {
John McCall9a34edb2010-10-19 01:40:49 +00003234 // If we're dealing with a decl but not a TagDecl, assume that
3235 // whatever routines created it handled the friendship aspect.
3236 if (TagD && !Tag)
John McCalld226f652010-08-21 09:40:31 +00003237 return 0;
Chandler Carruth0f4be742011-05-03 18:35:10 +00003238 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregord85bea22009-09-26 06:47:28 +00003239 }
John McCallac4df242011-03-22 23:00:04 +00003240
Richard Smithc7f81162013-03-18 22:52:47 +00003241 CXXScopeSpec &SS = DS.getTypeSpecScope();
3242 bool IsExplicitSpecialization =
3243 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3244 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3245 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3246 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3247 // nested-name-specifier unless it is an explicit instantiation
3248 // or an explicit specialization.
3249 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3250 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3251 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3252 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3253 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3254 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3255 << SS.getRange();
3256 return 0;
3257 }
3258
3259 // Track whether this decl-specifier declares anything.
3260 bool DeclaresAnything = true;
3261
3262 // Handle anonymous struct definitions.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003263 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall5e1cdac2011-10-07 06:10:15 +00003264 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00003265 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003266 if (getLangOpts().CPlusPlus ||
Douglas Gregora71c1292009-03-06 23:06:59 +00003267 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00003268 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00003269
Richard Smithc7f81162013-03-18 22:52:47 +00003270 DeclaresAnything = false;
Douglas Gregora71c1292009-03-06 23:06:59 +00003271 }
Francois Pichet8e161ed2010-11-23 06:07:27 +00003272 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003273
Richard Smithc7f81162013-03-18 22:52:47 +00003274 // Check for Microsoft C extension: anonymous struct member.
David Blaikie4e4d0842012-03-11 07:00:24 +00003275 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet8e161ed2010-11-23 06:07:27 +00003276 CurContext->isRecord() &&
3277 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3278 // Handle 2 kinds of anonymous struct:
3279 // struct STRUCT;
3280 // and
3281 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3282 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCall5e1cdac2011-10-07 06:10:15 +00003283 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet8e161ed2010-11-23 06:07:27 +00003284 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3285 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003286 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet8e161ed2010-11-23 06:07:27 +00003287 << DS.getSourceRange();
3288 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3289 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003290 }
Richard Smithc7f81162013-03-18 22:52:47 +00003291
3292 // Skip all the checks below if we have a type error.
3293 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3294 (TagD && TagD->isInvalidDecl()))
3295 return TagD;
3296
3297 if (getLangOpts().CPlusPlus &&
Douglas Gregora131d0f2010-07-13 06:24:26 +00003298 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3299 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3300 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithc7f81162013-03-18 22:52:47 +00003301 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3302 DeclaresAnything = false;
John McCallac4df242011-03-22 23:00:04 +00003303
John McCallac4df242011-03-22 23:00:04 +00003304 if (!DS.isMissingDeclaratorOk()) {
Richard Smithc7f81162013-03-18 22:52:47 +00003305 // Customize diagnostic for a typedef missing a name.
3306 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003307 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregora0ebd602010-07-16 15:40:40 +00003308 << DS.getSourceRange();
Richard Smithc7f81162013-03-18 22:52:47 +00003309 else
3310 DeclaresAnything = false;
Sebastian Redla4ed0d82008-12-28 15:28:59 +00003311 }
Mike Stump1eb44332009-09-09 15:08:12 +00003312
Richard Smithc7f81162013-03-18 22:52:47 +00003313 if (DS.isModulePrivateSpecified() &&
Douglas Gregore3895852011-09-12 18:37:38 +00003314 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3315 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3316 << Tag->getTagKind()
3317 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3318
Richard Smithc7f81162013-03-18 22:52:47 +00003319 ActOnDocumentableDecl(TagD);
3320
3321 // C 6.7/2:
3322 // A declaration [...] shall declare at least a declarator [...], a tag,
3323 // or the members of an enumeration.
3324 // C++ [dcl.dcl]p3:
3325 // [If there are no declarators], and except for the declaration of an
3326 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3327 // names into the program, or shall redeclare a name introduced by a
3328 // previous declaration.
3329 if (!DeclaresAnything) {
3330 // In C, we allow this as a (popular) extension / bug. Don't bother
3331 // producing further diagnostics for redundant qualifiers after this.
3332 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3333 return TagD;
3334 }
3335
3336 // C++ [dcl.stc]p1:
3337 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3338 // init-declarator-list of the declaration shall not be empty.
3339 // C++ [dcl.fct.spec]p1:
3340 // If a cv-qualifier appears in a decl-specifier-seq, the
3341 // init-declarator-list of the declaration shall not be empty.
3342 //
3343 // Spurious qualifiers here appear to be valid in C.
3344 unsigned DiagID = diag::warn_standalone_specifier;
3345 if (getLangOpts().CPlusPlus)
3346 DiagID = diag::ext_standalone_specifier;
3347
3348 // Note that a linkage-specification sets a storage class, but
3349 // 'extern "C" struct foo;' is actually valid and not theoretically
3350 // useless.
3351 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3352 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3353 Diag(DS.getStorageClassSpecLoc(), DiagID)
3354 << DeclSpec::getSpecifierName(SCS);
3355
Richard Smithec642442013-04-12 22:46:28 +00003356 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3357 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3358 << DeclSpec::getSpecifierName(TSCS);
Richard Smithc7f81162013-03-18 22:52:47 +00003359 if (DS.getTypeQualifiers()) {
3360 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3361 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3362 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3363 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3364 // Restrict is covered above.
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003365 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3366 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithc7f81162013-03-18 22:52:47 +00003367 }
3368
Eli Friedmanfc038e92011-12-17 00:36:09 +00003369 // Warn about ignored type attributes, for example:
3370 // __attribute__((aligned)) struct A;
Bill Wendlingad017fa2012-12-20 19:22:21 +00003371 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmanfc038e92011-12-17 00:36:09 +00003372 if (!DS.getAttributes().empty()) {
3373 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3374 if (TypeSpecType == DeclSpec::TST_class ||
3375 TypeSpecType == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003376 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmanfc038e92011-12-17 00:36:09 +00003377 TypeSpecType == DeclSpec::TST_union ||
3378 TypeSpecType == DeclSpec::TST_enum) {
3379 AttributeList* attrs = DS.getAttributes().getList();
3380 while (attrs) {
Michael Han45bed132012-10-04 16:42:52 +00003381 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmanfc038e92011-12-17 00:36:09 +00003382 << attrs->getName()
3383 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3384 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003385 TypeSpecType == DeclSpec::TST_union ? 2 :
3386 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmanfc038e92011-12-17 00:36:09 +00003387 attrs = attrs->getNext();
3388 }
3389 }
3390 }
John McCallac4df242011-03-22 23:00:04 +00003391
John McCalld226f652010-08-21 09:40:31 +00003392 return TagD;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003393}
3394
John McCall1d7c5282009-12-18 10:40:03 +00003395/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00003396/// check if there's an existing declaration that can't be overloaded.
3397///
3398/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00003399static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3400 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00003401 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00003402 DeclarationName Name,
3403 SourceLocation NameLoc,
3404 unsigned diagnostic) {
3405 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3406 Sema::ForRedeclaration);
3407 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00003408
John McCall1d7c5282009-12-18 10:40:03 +00003409 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00003410 return false;
3411
3412 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00003413 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidis2b642392010-09-23 14:26:01 +00003414 assert(PrevDecl && "Expected a non-null Decl");
3415
3416 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3417 return false;
John McCall68263142009-11-18 22:49:29 +00003418
John McCall1d7c5282009-12-18 10:40:03 +00003419 SemaRef.Diag(NameLoc, diagnostic) << Name;
3420 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00003421
3422 return true;
3423}
3424
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003425/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3426/// anonymous struct or union AnonRecord into the owning context Owner
3427/// and scope S. This routine will be invoked just after we realize
3428/// that an unnamed union or struct is actually an anonymous union or
3429/// struct, e.g.,
3430///
3431/// @code
3432/// union {
3433/// int i;
3434/// float f;
3435/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3436/// // f into the surrounding scope.x
3437/// @endcode
3438///
3439/// This routine is recursive, injecting the names of nested anonymous
3440/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00003441static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper6b9240e2013-07-05 19:34:19 +00003442 DeclContext *Owner,
3443 RecordDecl *AnonRecord,
3444 AccessSpecifier AS,
3445 SmallVectorImpl<NamedDecl *> &Chaining,
3446 bool MSAnonStruct) {
John McCall68263142009-11-18 22:49:29 +00003447 unsigned diagKind
3448 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3449 : diag::err_anonymous_struct_member_redecl;
3450
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003451 bool Invalid = false;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003452
3453 // Look every FieldDecl and IndirectFieldDecl with a name.
3454 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3455 DEnd = AnonRecord->decls_end();
3456 D != DEnd; ++D) {
3457 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3458 cast<NamedDecl>(*D)->getDeclName()) {
3459 ValueDecl *VD = cast<ValueDecl>(*D);
3460 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3461 VD->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003462 // C++ [class.union]p2:
3463 // The names of the members of an anonymous union shall be
3464 // distinct from the names of any other entity in the
3465 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003466 Invalid = true;
3467 } else {
3468 // C++ [class.union]p2:
3469 // For the purpose of name lookup, after the anonymous union
3470 // definition, the members of the anonymous union are
3471 // considered to have been defined in the scope in which the
3472 // anonymous union is declared.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003473 unsigned OldChainingSize = Chaining.size();
3474 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3475 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3476 PE = IF->chain_end(); PI != PE; ++PI)
3477 Chaining.push_back(*PI);
3478 else
3479 Chaining.push_back(VD);
3480
Francois Pichet87c2e122010-11-21 06:08:52 +00003481 assert(Chaining.size() >= 2);
3482 NamedDecl **NamedChain =
3483 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3484 for (unsigned i = 0; i < Chaining.size(); i++)
3485 NamedChain[i] = Chaining[i];
3486
3487 IndirectFieldDecl* IndirectField =
Francois Pichet8e161ed2010-11-23 06:07:27 +00003488 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3489 VD->getIdentifier(), VD->getType(),
Francois Pichet87c2e122010-11-21 06:08:52 +00003490 NamedChain, Chaining.size());
3491
3492 IndirectField->setAccess(AS);
3493 IndirectField->setImplicit();
3494 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallaec03712010-05-21 20:45:30 +00003495
3496 // That includes picking up the appropriate access specifier.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003497 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet87c2e122010-11-21 06:08:52 +00003498
Francois Pichet8e161ed2010-11-23 06:07:27 +00003499 Chaining.resize(OldChainingSize);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003500 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003501 }
3502 }
3503
3504 return Invalid;
3505}
3506
Douglas Gregor16573fa2010-04-19 22:54:31 +00003507/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3508/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCalld931b082010-08-26 03:08:43 +00003509/// illegal input values are mapped to SC_None.
3510static StorageClass
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003511StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3512 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3513 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3514 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregor16573fa2010-04-19 22:54:31 +00003515 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00003516 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003517 case DeclSpec::SCS_extern:
3518 if (DS.isExternInLinkageSpec())
3519 return SC_None;
3520 return SC_Extern;
John McCalld931b082010-08-26 03:08:43 +00003521 case DeclSpec::SCS_static: return SC_Static;
3522 case DeclSpec::SCS_auto: return SC_Auto;
3523 case DeclSpec::SCS_register: return SC_Register;
3524 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003525 // Illegal SCSs map to None: error reporting is up to the caller.
3526 case DeclSpec::SCS_mutable: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00003527 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003528 }
3529 llvm_unreachable("unknown storage class specifier");
3530}
3531
Francois Pichet8e161ed2010-11-23 06:07:27 +00003532/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003533/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgacbabf12012-02-03 15:47:04 +00003534/// (C++ [class.union]) and a C11 feature; anonymous structures
3535/// are a C11 feature and GNU C++ extension.
John McCalld226f652010-08-21 09:40:31 +00003536Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3537 AccessSpecifier AS,
3538 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003539 DeclContext *Owner = Record->getDeclContext();
3540
3541 // Diagnose whether this anonymous struct/union is an extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00003542 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003543 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikie4e4d0842012-03-11 07:00:24 +00003544 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003545 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikie4e4d0842012-03-11 07:00:24 +00003546 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003547 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003549 // C and C++ require different kinds of checks for anonymous
3550 // structs/unions.
3551 bool Invalid = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00003552 if (getLangOpts().CPlusPlus) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003553 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00003554 unsigned DiagID;
David Blaikie2b79c322011-10-19 22:43:29 +00003555 if (Record->isUnion()) {
3556 // C++ [class.union]p6:
3557 // Anonymous unions declared in a named namespace or in the
3558 // global namespace shall be declared static.
3559 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3560 (isa<TranslationUnitDecl>(Owner) ||
3561 (isa<NamespaceDecl>(Owner) &&
3562 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie82c8ca12011-10-20 02:49:08 +00003563 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3564 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie2b79c322011-10-19 22:43:29 +00003565
3566 // Recover by adding 'static'.
3567 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3568 PrevSpec, DiagID);
3569 }
3570 // C++ [class.union]p6:
3571 // A storage class is not allowed in a declaration of an
3572 // anonymous union in a class scope.
3573 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3574 isa<RecordDecl>(Owner)) {
3575 Diag(DS.getStorageClassSpecLoc(),
David Blaikief6f876c2011-10-20 02:10:55 +00003576 diag::err_anonymous_union_with_storage_spec)
3577 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie2b79c322011-10-19 22:43:29 +00003578
3579 // Recover by removing the storage specifier.
David Blaikied662a792011-10-19 22:56:21 +00003580 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3581 SourceLocation(),
David Blaikie2b79c322011-10-19 22:43:29 +00003582 PrevSpec, DiagID);
3583 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003584 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003585
Douglas Gregor7604f642011-05-09 23:05:33 +00003586 // Ignore const/volatile/restrict qualifiers.
3587 if (DS.getTypeQualifiers()) {
3588 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3589 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003590 << Record->isUnion() << "const"
Douglas Gregor7604f642011-05-09 23:05:33 +00003591 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3592 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003593 Diag(DS.getVolatileSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003594 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003595 << Record->isUnion() << "volatile"
Douglas Gregor7604f642011-05-09 23:05:33 +00003596 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3597 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003598 Diag(DS.getRestrictSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003599 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003600 << Record->isUnion() << "restrict"
Douglas Gregor7604f642011-05-09 23:05:33 +00003601 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003602 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3603 Diag(DS.getAtomicSpecLoc(),
3604 diag::ext_anonymous_struct_union_qualified)
3605 << Record->isUnion() << "_Atomic"
3606 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor7604f642011-05-09 23:05:33 +00003607
3608 DS.ClearTypeQualifiers();
3609 }
3610
Mike Stump1eb44332009-09-09 15:08:12 +00003611 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003612 // The member-specification of an anonymous union shall only
3613 // define non-static data members. [Note: nested types and
3614 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003615 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3616 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003617 Mem != MemEnd; ++Mem) {
3618 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3619 // C++ [class.union]p3:
3620 // An anonymous union shall not have private or protected
3621 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00003622 assert(FD->getAccess() != AS_none);
3623 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003624 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3625 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3626 Invalid = true;
3627 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003628
Sean Huntcf34e752011-05-16 22:41:40 +00003629 // C++ [class.union]p1
3630 // An object of a class with a non-trivial constructor, a non-trivial
3631 // copy constructor, a non-trivial destructor, or a non-trivial copy
3632 // assignment operator cannot be a member of a union, nor can an
3633 // array of such objects.
Richard Smithe7d7c392011-10-19 20:41:51 +00003634 if (CheckNontrivialField(FD))
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003635 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003636 } else if ((*Mem)->isImplicit()) {
3637 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00003638 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3639 // This is a type that showed up in an
3640 // elaborated-type-specifier inside the anonymous struct or
3641 // union, but which actually declares a type outside of the
3642 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003643 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3644 if (!MemRecord->isAnonymousStructOrUnion() &&
3645 MemRecord->getDeclName()) {
Francois Pichet538e0d02010-09-08 11:32:25 +00003646 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003647 if (getLangOpts().MicrosoftExt)
Francois Pichet538e0d02010-09-08 11:32:25 +00003648 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3649 << (int)Record->isUnion();
3650 else {
3651 // This is a nested type declaration.
3652 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3653 << (int)Record->isUnion();
3654 Invalid = true;
3655 }
Richard Smithc5f7d6a2013-01-28 00:54:05 +00003656 } else {
3657 // This is an anonymous type definition within another anonymous type.
3658 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3659 // not part of standard C++.
3660 Diag(MemRecord->getLocation(),
Richard Smithf2705192013-01-31 03:11:12 +00003661 diag::ext_anonymous_record_with_anonymous_type)
3662 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003663 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00003664 } else if (isa<AccessSpecDecl>(*Mem)) {
3665 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003666 } else {
3667 // We have something that isn't a non-static data
3668 // member. Complain about it.
3669 unsigned DK = diag::err_anonymous_record_bad_member;
3670 if (isa<TypeDecl>(*Mem))
3671 DK = diag::err_anonymous_record_with_type;
3672 else if (isa<FunctionDecl>(*Mem))
3673 DK = diag::err_anonymous_record_with_function;
3674 else if (isa<VarDecl>(*Mem))
3675 DK = diag::err_anonymous_record_with_static;
Francois Pichet538e0d02010-09-08 11:32:25 +00003676
3677 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003678 if (getLangOpts().MicrosoftExt &&
Francois Pichet538e0d02010-09-08 11:32:25 +00003679 DK == diag::err_anonymous_record_with_type)
3680 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003681 << (int)Record->isUnion();
Francois Pichet538e0d02010-09-08 11:32:25 +00003682 else {
3683 Diag((*Mem)->getLocation(), DK)
3684 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003685 Invalid = true;
Francois Pichet538e0d02010-09-08 11:32:25 +00003686 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003687 }
3688 }
Mike Stump1eb44332009-09-09 15:08:12 +00003689 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003690
3691 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003692 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikie4e4d0842012-03-11 07:00:24 +00003693 << (int)getLangOpts().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003694 Invalid = true;
3695 }
3696
John McCalleb692e02009-10-22 23:31:08 +00003697 // Mock up a declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003698 Declarator Dc(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00003699 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00003700 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00003701
Mike Stump1eb44332009-09-09 15:08:12 +00003702 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003703 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003704 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003705 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003706 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003707 Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003708 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003709 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00003710 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003711 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003712 /*InitStyle=*/ICIS_NoInit);
John McCallaec03712010-05-21 20:45:30 +00003713 Anon->setAccess(AS);
David Blaikie4e4d0842012-03-11 07:00:24 +00003714 if (getLangOpts().CPlusPlus)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003715 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003716 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00003717 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003718 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003719 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003720 // mutable can only appear on non-static class members, so it's always
3721 // an error here
3722 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3723 Invalid = true;
John McCalld931b082010-08-26 03:08:43 +00003724 SC = SC_None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003725 }
3726
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003727 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003728 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003729 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003730 Context.getTypeDeclType(Record),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003731 TInfo, SC);
Richard Smith16ee8192011-09-18 00:06:34 +00003732
3733 // Default-initialize the implicit variable. This initialization will be
3734 // trivial in almost all cases, except if a union member has an in-class
3735 // initializer:
3736 // union { int n = 0; };
3737 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003738 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003739 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003740
3741 // Add the anonymous struct/union object to the current
3742 // context. We'll be referencing this object when we refer to one of
3743 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003744 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00003745
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003746 // Inject the members of the anonymous struct/union into the owning
3747 // context and into the identifier resolver chain for name lookup
3748 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003749 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet87c2e122010-11-21 06:08:52 +00003750 Chain.push_back(Anon);
3751
Francois Pichet8e161ed2010-11-23 06:07:27 +00003752 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3753 Chain, false))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003754 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003755
3756 // Mark this as an anonymous struct/union type. Note that we do not
3757 // do this until after we have already checked and injected the
3758 // members of this anonymous struct/union type, because otherwise
3759 // the members could be injected twice: once by DeclContext when it
3760 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00003761 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003762 Record->setAnonymousStructOrUnion(true);
3763
3764 if (Invalid)
3765 Anon->setInvalidDecl();
3766
John McCalld226f652010-08-21 09:40:31 +00003767 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003768}
3769
Francois Pichet8e161ed2010-11-23 06:07:27 +00003770/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3771/// Microsoft C anonymous structure.
3772/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3773/// Example:
3774///
3775/// struct A { int a; };
3776/// struct B { struct A; int b; };
3777///
3778/// void foo() {
3779/// B var;
3780/// var.a = 3;
3781/// }
3782///
3783Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3784 RecordDecl *Record) {
3785
3786 // If there is no Record, get the record via the typedef.
3787 if (!Record)
3788 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3789
3790 // Mock up a declarator.
3791 Declarator Dc(DS, Declarator::TypeNameContext);
3792 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3793 assert(TInfo && "couldn't build declarator info for anonymous struct");
3794
3795 // Create a declaration for this anonymous struct.
3796 NamedDecl* Anon = FieldDecl::Create(Context,
3797 cast<RecordDecl>(CurContext),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003798 DS.getLocStart(),
3799 DS.getLocStart(),
Francois Pichet8e161ed2010-11-23 06:07:27 +00003800 /*IdentifierInfo=*/0,
3801 Context.getTypeDeclType(Record),
3802 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003803 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003804 /*InitStyle=*/ICIS_NoInit);
Francois Pichet8e161ed2010-11-23 06:07:27 +00003805 Anon->setImplicit();
3806
3807 // Add the anonymous struct object to the current context.
3808 CurContext->addDecl(Anon);
3809
3810 // Inject the members of the anonymous struct into the current
3811 // context and into the identifier resolver chain for name lookup
3812 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003813 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003814 Chain.push_back(Anon);
3815
Nico Weberee625af2012-02-01 00:41:00 +00003816 RecordDecl *RecordDef = Record->getDefinition();
3817 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3818 RecordDef, AS_none,
3819 Chain, true))
Francois Pichet8e161ed2010-11-23 06:07:27 +00003820 Anon->setInvalidDecl();
3821
3822 return Anon;
3823}
Steve Narofff0090632007-09-02 02:04:30 +00003824
Douglas Gregor10bd3682008-11-17 22:58:34 +00003825/// GetNameForDeclarator - Determine the full declaration name for the
3826/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00003827DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00003828 return GetNameFromUnqualifiedId(D.getName());
3829}
3830
Abramo Bagnara25777432010-08-11 22:01:17 +00003831/// \brief Retrieves the declaration name from a parsed unqualified-id.
3832DeclarationNameInfo
3833Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3834 DeclarationNameInfo NameInfo;
3835 NameInfo.setLoc(Name.StartLocation);
3836
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003837 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00003838
Fariborz Jahanian98a54032011-07-12 17:16:56 +00003839 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnara25777432010-08-11 22:01:17 +00003840 case UnqualifiedId::IK_Identifier:
3841 NameInfo.setName(Name.Identifier);
3842 NameInfo.setLoc(Name.StartLocation);
3843 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00003844
Abramo Bagnara25777432010-08-11 22:01:17 +00003845 case UnqualifiedId::IK_OperatorFunctionId:
3846 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3847 Name.OperatorFunctionId.Operator));
3848 NameInfo.setLoc(Name.StartLocation);
3849 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3850 = Name.OperatorFunctionId.SymbolLocations[0];
3851 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3852 = Name.EndLocation.getRawEncoding();
3853 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003854
Abramo Bagnara25777432010-08-11 22:01:17 +00003855 case UnqualifiedId::IK_LiteralOperatorId:
3856 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3857 Name.Identifier));
3858 NameInfo.setLoc(Name.StartLocation);
3859 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3860 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003861
Abramo Bagnara25777432010-08-11 22:01:17 +00003862 case UnqualifiedId::IK_ConversionFunctionId: {
3863 TypeSourceInfo *TInfo;
3864 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3865 if (Ty.isNull())
3866 return DeclarationNameInfo();
3867 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3868 Context.getCanonicalType(Ty)));
3869 NameInfo.setLoc(Name.StartLocation);
3870 NameInfo.setNamedTypeInfo(TInfo);
3871 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00003872 }
Abramo Bagnara25777432010-08-11 22:01:17 +00003873
3874 case UnqualifiedId::IK_ConstructorName: {
3875 TypeSourceInfo *TInfo;
3876 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3877 if (Ty.isNull())
3878 return DeclarationNameInfo();
3879 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3880 Context.getCanonicalType(Ty)));
3881 NameInfo.setLoc(Name.StartLocation);
3882 NameInfo.setNamedTypeInfo(TInfo);
3883 return NameInfo;
3884 }
3885
3886 case UnqualifiedId::IK_ConstructorTemplateId: {
3887 // In well-formed code, we can only have a constructor
3888 // template-id that refers to the current context, so go there
3889 // to find the actual type being constructed.
3890 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3891 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3892 return DeclarationNameInfo();
3893
3894 // Determine the type of the class being constructed.
3895 QualType CurClassType = Context.getTypeDeclType(CurClass);
3896
3897 // FIXME: Check two things: that the template-id names the same type as
3898 // CurClassType, and that the template-id does not occur when the name
3899 // was qualified.
3900
3901 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3902 Context.getCanonicalType(CurClassType)));
3903 NameInfo.setLoc(Name.StartLocation);
3904 // FIXME: should we retrieve TypeSourceInfo?
3905 NameInfo.setNamedTypeInfo(0);
3906 return NameInfo;
3907 }
3908
3909 case UnqualifiedId::IK_DestructorName: {
3910 TypeSourceInfo *TInfo;
3911 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3912 if (Ty.isNull())
3913 return DeclarationNameInfo();
3914 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3915 Context.getCanonicalType(Ty)));
3916 NameInfo.setLoc(Name.StartLocation);
3917 NameInfo.setNamedTypeInfo(TInfo);
3918 return NameInfo;
3919 }
3920
3921 case UnqualifiedId::IK_TemplateId: {
John McCall2b5289b2010-08-23 07:28:44 +00003922 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00003923 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3924 return Context.getNameForTemplate(TName, TNameLoc);
3925 }
3926
3927 } // switch (Name.getKind())
3928
David Blaikieb219cfc2011-09-23 05:06:16 +00003929 llvm_unreachable("Unknown name kind");
Douglas Gregor10bd3682008-11-17 22:58:34 +00003930}
3931
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003932static QualType getCoreType(QualType Ty) {
3933 do {
3934 if (Ty->isPointerType() || Ty->isReferenceType())
3935 Ty = Ty->getPointeeType();
3936 else if (Ty->isArrayType())
3937 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3938 else
3939 return Ty.withoutLocalFastQualifiers();
3940 } while (true);
3941}
3942
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00003943/// hasSimilarParameters - Determine whether the C++ functions Declaration
3944/// and Definition have "nearly" matching parameters. This heuristic is
3945/// used to improve diagnostics in the case where an out-of-line function
3946/// definition doesn't match any declaration within the class or namespace.
3947/// Also sets Params to the list of indices to the parameters that differ
3948/// between the declaration and the definition. If hasSimilarParameters
3949/// returns true and Params is empty, then all of the parameters match.
3950static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003951 FunctionDecl *Declaration,
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003952 FunctionDecl *Definition,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003953 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003954 Params.clear();
Douglas Gregor584049d2008-12-15 23:53:10 +00003955 if (Declaration->param_size() != Definition->param_size())
3956 return false;
3957 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3958 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3959 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3960
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003961 // The parameter types are identical
Matt Beaumont-Gay903d6dc2011-08-23 01:35:51 +00003962 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003963 continue;
3964
3965 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3966 QualType DefParamBaseTy = getCoreType(DefParamTy);
3967 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3968 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3969
3970 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3971 (DeclTyName && DeclTyName == DefTyName))
3972 Params.push_back(Idx);
3973 else // The two parameters aren't even close
Douglas Gregor584049d2008-12-15 23:53:10 +00003974 return false;
3975 }
3976
3977 return true;
3978}
3979
John McCall63b43852010-04-29 23:50:39 +00003980/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3981/// declarator needs to be rebuilt in the current instantiation.
3982/// Any bits of declarator which appear before the name are valid for
3983/// consideration here. That's specifically the type in the decl spec
3984/// and the base type in any member-pointer chunks.
3985static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3986 DeclarationName Name) {
3987 // The types we specifically need to rebuild are:
3988 // - typenames, typeofs, and decltypes
3989 // - types which will become injected class names
3990 // Of course, we also need to rebuild any type referencing such a
3991 // type. It's safest to just say "dependent", but we call out a
3992 // few cases here.
3993
3994 DeclSpec &DS = D.getMutableDeclSpec();
3995 switch (DS.getTypeSpecType()) {
3996 case DeclSpec::TST_typename:
3997 case DeclSpec::TST_typeofType:
Eli Friedmanb001de72011-10-06 23:00:33 +00003998 case DeclSpec::TST_underlyingType:
3999 case DeclSpec::TST_atomic: {
John McCall63b43852010-04-29 23:50:39 +00004000 // Grab the type from the parser.
4001 TypeSourceInfo *TSI = 0;
John McCallb3d87482010-08-24 05:47:05 +00004002 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall63b43852010-04-29 23:50:39 +00004003 if (T.isNull() || !T->isDependentType()) break;
4004
4005 // Make sure there's a type source info. This isn't really much
4006 // of a waste; most dependent types should have type source info
4007 // attached already.
4008 if (!TSI)
4009 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4010
4011 // Rebuild the type in the current instantiation.
4012 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4013 if (!TSI) return true;
4014
4015 // Store the new type back in the decl spec.
John McCallb3d87482010-08-24 05:47:05 +00004016 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4017 DS.UpdateTypeRep(LocType);
4018 break;
4019 }
4020
Richard Smithc4a83912012-10-01 20:35:07 +00004021 case DeclSpec::TST_decltype:
John McCallb3d87482010-08-24 05:47:05 +00004022 case DeclSpec::TST_typeofExpr: {
4023 Expr *E = DS.getRepAsExpr();
John McCall60d7b3a2010-08-24 06:29:42 +00004024 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallb3d87482010-08-24 05:47:05 +00004025 if (Result.isInvalid()) return true;
4026 DS.UpdateExprRep(Result.get());
John McCall63b43852010-04-29 23:50:39 +00004027 break;
4028 }
4029
4030 default:
4031 // Nothing to do for these decl specs.
4032 break;
4033 }
4034
4035 // It doesn't matter what order we do this in.
4036 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4037 DeclaratorChunk &Chunk = D.getTypeObject(I);
4038
4039 // The only type information in the declarator which can come
4040 // before the declaration name is the base type of a member
4041 // pointer.
4042 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4043 continue;
4044
4045 // Rebuild the scope specifier in-place.
4046 CXXScopeSpec &SS = Chunk.Mem.Scope();
4047 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4048 return true;
4049 }
4050
4051 return false;
4052}
4053
Anders Carlsson3242ee02011-07-04 16:28:17 +00004054Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00004055 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004056 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004057
4058 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregore7be1092012-04-30 18:13:01 +00004059 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004060 Dcl->setTopLevelDeclInObjCContainer();
4061
4062 return Dcl;
John McCall7cd088e2010-08-24 07:21:54 +00004063}
4064
Richard Smith162e1c12011-04-15 14:24:37 +00004065/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4066/// If T is the name of a class, then each of the following shall have a
4067/// name different from T:
4068/// - every static data member of class T;
4069/// - every member function of class T
4070/// - every member of class T that is itself a type;
4071/// \returns true if the declaration name violates these rules.
4072bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4073 DeclarationNameInfo NameInfo) {
4074 DeclarationName Name = NameInfo.getName();
4075
4076 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4077 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4078 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4079 return true;
4080 }
4081
4082 return false;
4083}
Douglas Gregor42acead2012-03-17 23:06:31 +00004084
Douglas Gregor69605872012-03-28 16:01:27 +00004085/// \brief Diagnose a declaration whose declarator-id has the given
4086/// nested-name-specifier.
4087///
4088/// \param SS The nested-name-specifier of the declarator-id.
4089///
4090/// \param DC The declaration context to which the nested-name-specifier
4091/// resolves.
4092///
4093/// \param Name The name of the entity being declared.
4094///
4095/// \param Loc The location of the name of the entity being declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004096///
4097/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregor69605872012-03-28 16:01:27 +00004098bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor42acead2012-03-17 23:06:31 +00004099 DeclarationName Name,
Douglas Gregor69605872012-03-28 16:01:27 +00004100 SourceLocation Loc) {
4101 DeclContext *Cur = CurContext;
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004102 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregor69605872012-03-28 16:01:27 +00004103 Cur = Cur->getParent();
4104
4105 // C++ [dcl.meaning]p1:
4106 // A declarator-id shall not be qualified except for the definition
4107 // of a member function (9.3) or static data member (9.4) outside of
4108 // its class, the definition or explicit instantiation of a function
4109 // or variable member of a namespace outside of its namespace, or the
4110 // definition of an explicit specialization outside of its namespace,
4111 // or the declaration of a friend function that is a member of
4112 // another class or namespace (11.3). [...]
4113
4114 // The user provided a superfluous scope specifier that refers back to the
4115 // class or namespaces in which the entity is already declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004116 //
4117 // class X {
4118 // void X::f();
4119 // };
Douglas Gregor69605872012-03-28 16:01:27 +00004120 if (Cur->Equals(DC)) {
Douglas Gregor75379452012-09-13 20:16:20 +00004121 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4122 : diag::err_member_extra_qualification)
Douglas Gregor42acead2012-03-17 23:06:31 +00004123 << Name << FixItHint::CreateRemoval(SS.getRange());
4124 SS.clear();
4125 return false;
4126 }
Douglas Gregor69605872012-03-28 16:01:27 +00004127
4128 // Check whether the qualifying scope encloses the scope of the original
4129 // declaration.
4130 if (!Cur->Encloses(DC)) {
4131 if (Cur->isRecord())
4132 Diag(Loc, diag::err_member_qualification)
4133 << Name << SS.getRange();
4134 else if (isa<TranslationUnitDecl>(DC))
4135 Diag(Loc, diag::err_invalid_declarator_global_scope)
4136 << Name << SS.getRange();
4137 else if (isa<FunctionDecl>(Cur))
4138 Diag(Loc, diag::err_invalid_declarator_in_function)
4139 << Name << SS.getRange();
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004140 else if (isa<BlockDecl>(Cur))
4141 Diag(Loc, diag::err_invalid_declarator_in_block)
4142 << Name << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004143 else
4144 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smitha1c4f7c2012-04-13 04:07:40 +00004145 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004146
Douglas Gregor42acead2012-03-17 23:06:31 +00004147 return true;
Douglas Gregor69605872012-03-28 16:01:27 +00004148 }
4149
4150 if (Cur->isRecord()) {
4151 // Cannot qualify members within a class.
4152 Diag(Loc, diag::err_member_qualification)
4153 << Name << SS.getRange();
4154 SS.clear();
4155
4156 // C++ constructors and destructors with incorrect scopes can break
4157 // our AST invariants by having the wrong underlying types. If
4158 // that's the case, then drop this declaration entirely.
4159 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4160 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4161 !Context.hasSameType(Name.getCXXNameType(),
4162 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4163 return true;
4164
4165 return false;
4166 }
Douglas Gregor42acead2012-03-17 23:06:31 +00004167
Douglas Gregor69605872012-03-28 16:01:27 +00004168 // C++11 [dcl.meaning]p1:
4169 // [...] "The nested-name-specifier of the qualified declarator-id shall
4170 // not begin with a decltype-specifer"
4171 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4172 while (SpecLoc.getPrefix())
4173 SpecLoc = SpecLoc.getPrefix();
4174 if (dyn_cast_or_null<DecltypeType>(
4175 SpecLoc.getNestedNameSpecifier()->getAsType()))
4176 Diag(Loc, diag::err_decltype_in_declarator)
4177 << SpecLoc.getTypeLoc().getSourceRange();
4178
Douglas Gregor42acead2012-03-17 23:06:31 +00004179 return false;
4180}
4181
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00004182NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4183 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnara25777432010-08-11 22:01:17 +00004184 // TODO: consider using NameInfo for diagnostic.
4185 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4186 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00004187
Chris Lattnere80a59c2007-07-25 00:24:17 +00004188 // All of these full declarators require an identifier. If it doesn't have
4189 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00004190 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00004191 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004192 Diag(D.getDeclSpec().getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004193 diag::err_declarator_need_ident)
4194 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00004195 return 0;
Douglas Gregor56c04582010-12-16 00:46:58 +00004196 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4197 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004198
Chris Lattner31e05722007-08-26 06:24:45 +00004199 // The scope passed in may not be a decl scope. Zip up the scope tree until
4200 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00004201 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004202 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00004203 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004204
John McCall63b43852010-04-29 23:50:39 +00004205 DeclContext *DC = CurContext;
4206 if (D.getCXXScopeSpec().isInvalid())
4207 D.setInvalidType();
4208 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6ccab972010-12-16 01:14:37 +00004209 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4210 UPPC_DeclarationQualifier))
4211 return 0;
4212
John McCall63b43852010-04-29 23:50:39 +00004213 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4214 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4215 if (!DC) {
4216 // If we could not compute the declaration context, it's because the
4217 // declaration context is dependent but does not refer to a class,
4218 // class template, or class template partial specialization. Complain
4219 // and return early, to avoid the coming semantic disaster.
4220 Diag(D.getIdentifierLoc(),
4221 diag::err_template_qualified_declarator_no_match)
4222 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4223 << D.getCXXScopeSpec().getRange();
John McCalld226f652010-08-21 09:40:31 +00004224 return 0;
John McCall63b43852010-04-29 23:50:39 +00004225 }
John McCall63b43852010-04-29 23:50:39 +00004226 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00004227
John McCall63b43852010-04-29 23:50:39 +00004228 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00004229 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCalld226f652010-08-21 09:40:31 +00004230 return 0;
John McCall63b43852010-04-29 23:50:39 +00004231
Douglas Gregor69605872012-03-28 16:01:27 +00004232 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4233 Diag(D.getIdentifierLoc(),
4234 diag::err_member_def_undefined_record)
4235 << Name << DC << D.getCXXScopeSpec().getRange();
4236 D.setInvalidType();
4237 } else if (!D.getDeclSpec().isFriendSpecified()) {
4238 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4239 Name, D.getIdentifierLoc())) {
4240 if (DC->isRecord())
Douglas Gregor42acead2012-03-17 23:06:31 +00004241 return 0;
Douglas Gregor69605872012-03-28 16:01:27 +00004242
4243 D.setInvalidType();
Douglas Gregor922fff22010-10-13 22:19:53 +00004244 }
John McCall63b43852010-04-29 23:50:39 +00004245 }
4246
4247 // Check whether we need to rebuild the type of the given
4248 // declaration in the current instantiation.
4249 if (EnteringContext && IsDependentContext &&
4250 TemplateParamLists.size() != 0) {
4251 ContextRAII SavedContext(*this, DC);
4252 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4253 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00004254 }
4255 }
Richard Smith162e1c12011-04-15 14:24:37 +00004256
4257 if (DiagnoseClassNameShadow(DC, NameInfo))
4258 // If this is a typedef, we'll end up spewing multiple diagnostics.
4259 // Just return early; it's safer.
4260 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4261 return 0;
Douglas Gregora6e937c2010-10-15 13:21:21 +00004262
John McCallbf1a0282010-06-04 23:28:52 +00004263 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4264 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004265
Douglas Gregord0937222010-12-13 22:49:22 +00004266 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4267 UPPC_DeclarationType))
4268 D.setInvalidType();
4269
Abramo Bagnara25777432010-08-11 22:01:17 +00004270 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00004271 ForRedeclaration);
4272
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004273 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00004274 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00004275 bool IsLinkageLookup = false;
Richard Smithdd9459f2013-08-13 18:18:50 +00004276 bool CreateBuiltins = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004277
4278 // If the declaration we're planning to build will be a function
4279 // or object with linkage, then look for another declaration with
4280 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smithdd9459f2013-08-13 18:18:50 +00004281 //
4282 // If the declaration we're planning to build will be declared with
4283 // external linkage in the translation unit, create any builtin with
4284 // the same name.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004285 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4286 /* Do nothing*/;
Richard Smithdd9459f2013-08-13 18:18:50 +00004287 else if (CurContext->isFunctionOrMethod() &&
4288 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4289 R->isFunctionType())) {
John McCall68263142009-11-18 22:49:29 +00004290 IsLinkageLookup = true;
Richard Smithdd9459f2013-08-13 18:18:50 +00004291 CreateBuiltins =
4292 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4293 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4294 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4295 CreateBuiltins = true;
John McCall68263142009-11-18 22:49:29 +00004296
4297 if (IsLinkageLookup)
4298 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004299
Richard Smithdd9459f2013-08-13 18:18:50 +00004300 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004301 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00004302 LookupQualifiedName(Previous, DC);
4303
Douglas Gregor69605872012-03-28 16:01:27 +00004304 // C++ [dcl.meaning]p1:
4305 // When the declarator-id is qualified, the declaration shall refer to a
4306 // previously declared member of the class or namespace to which the
4307 // qualifier refers (or, in the case of a namespace, of an element of the
4308 // inline namespace set of that namespace (7.3.1)) or to a specialization
4309 // thereof; [...]
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004310 //
Douglas Gregor69605872012-03-28 16:01:27 +00004311 // Note that we already checked the context above, and that we do not have
4312 // enough information to make sure that Previous contains the declaration
4313 // we want to match. For example, given:
Douglas Gregor584049d2008-12-15 23:53:10 +00004314 //
Douglas Gregor9d350972008-12-12 08:25:50 +00004315 // class X {
4316 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00004317 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00004318 // };
4319 //
Douglas Gregor584049d2008-12-15 23:53:10 +00004320 // void X::f(int) { } // ill-formed
4321 //
Douglas Gregor69605872012-03-28 16:01:27 +00004322 // In this case, Previous will point to the overload set
Douglas Gregor584049d2008-12-15 23:53:10 +00004323 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00004324 // matches.
Douglas Gregor69605872012-03-28 16:01:27 +00004325
4326 // C++ [dcl.meaning]p1:
4327 // [...] the member shall not merely have been introduced by a
4328 // using-declaration in the scope of the class or namespace nominated by
4329 // the nested-name-specifier of the declarator-id.
4330 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004331 }
4332
John McCall68263142009-11-18 22:49:29 +00004333 if (Previous.isSingleResult() &&
4334 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00004335 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004336 if (!D.isInvalidType())
Douglas Gregorcb8f9512011-10-20 17:58:49 +00004337 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4338 Previous.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004339
Douglas Gregor72c3f312008-12-05 18:15:24 +00004340 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00004341 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00004342 }
4343
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004344 // In C++, the previous declaration we find might be a tag type
4345 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00004346 // tag type. Note that this does does not apply if we're declaring a
4347 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00004348 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00004349 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00004350 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004351
Richard Smith3cdbbdc2013-03-06 01:37:38 +00004352 // Check that there are no default arguments other than in the parameters
4353 // of a function declaration (C++ only).
4354 if (getLangOpts().CPlusPlus)
4355 CheckExtraCXXDefaultArguments(D);
4356
Nico Webere6bb76c2012-12-23 00:40:46 +00004357 NamedDecl *New;
4358
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004359 bool AddToScope = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00004360 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00004361 if (TemplateParamLists.size()) {
4362 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCalld226f652010-08-21 09:40:31 +00004363 return 0;
Douglas Gregore542c862009-06-23 23:11:28 +00004364 }
Mike Stump1eb44332009-09-09 15:08:12 +00004365
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004366 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004367 } else if (R->isFunctionType()) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004368 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004369 TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004370 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004371 } else {
Larisse Voufoef4579c2013-08-06 01:03:05 +00004372 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4373 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004374 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004375
4376 if (New == 0)
John McCalld226f652010-08-21 09:40:31 +00004377 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004378
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004379 // If this has an identifier and is not an invalid redeclaration or
4380 // function template specialization, add it to the scope stack.
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004381 if (New->getDeclName() && AddToScope &&
Richard Smitha41c97a2013-09-20 01:15:31 +00004382 !(D.isRedeclaration() && New->isInvalidDecl())) {
4383 // Only make a locally-scoped extern declaration visible if it is the first
4384 // declaration of this entity. Qualified lookup for such an entity should
4385 // only find this declaration if there is no visible declaration of it.
4386 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4387 PushOnScopeChains(New, S, AddToContext);
4388 if (!AddToContext)
4389 CurContext->addHiddenDecl(New);
4390 }
Mike Stump1eb44332009-09-09 15:08:12 +00004391
John McCalld226f652010-08-21 09:40:31 +00004392 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00004393}
4394
Abramo Bagnara88adb982012-11-08 16:27:30 +00004395/// Helper method to turn variable array types into constant array
4396/// types in certain situations which would otherwise be errors (for
4397/// GCC compatibility).
Eli Friedman1ca48132009-02-21 00:44:51 +00004398static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4399 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00004400 bool &SizeIsNegative,
4401 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004402 // This method tries to turn a variable array into a constant
4403 // array even when the size isn't an ICE. This is necessary
4404 // for compatibility with code that depends on gcc's buggy
4405 // constant expression folding, like struct {char x[(int)(char*)2];}
4406 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004407 Oversized = 0;
4408
4409 if (T->isDependentType())
4410 return QualType();
4411
John McCall0953e762009-09-24 19:53:00 +00004412 QualifierCollector Qs;
4413 const Type *Ty = Qs.strip(T);
4414
4415 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004416 QualType Pointee = PTy->getPointeeType();
4417 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00004418 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4419 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00004420 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00004421 FixedType = Context.getPointerType(FixedType);
John McCall49f4e1c2010-12-10 11:01:00 +00004422 return Qs.apply(Context, FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00004423 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004424 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4425 QualType Inner = PTy->getInnerType();
4426 QualType FixedType =
4427 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4428 Oversized);
4429 if (FixedType.isNull()) return FixedType;
4430 FixedType = Context.getParenType(FixedType);
4431 return Qs.apply(Context, FixedType);
4432 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004433
4434 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00004435 if (!VLATy)
4436 return QualType();
4437 // FIXME: We should probably handle this case
4438 if (VLATy->getElementType()->isVariablyModifiedType())
4439 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004440
Richard Smithaa9c3502011-12-07 00:43:50 +00004441 llvm::APSInt Res;
Eli Friedman1ca48132009-02-21 00:44:51 +00004442 if (!VLATy->getSizeExpr() ||
Richard Smithaa9c3502011-12-07 00:43:50 +00004443 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedman1ca48132009-02-21 00:44:51 +00004444 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00004445
Douglas Gregor2767ce22010-08-18 00:39:00 +00004446 // Check whether the array size is negative.
Douglas Gregor2767ce22010-08-18 00:39:00 +00004447 if (Res.isSigned() && Res.isNegative()) {
4448 SizeIsNegative = true;
4449 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004450 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004451
Douglas Gregor2767ce22010-08-18 00:39:00 +00004452 // Check whether the array is too large to be addressed.
4453 unsigned ActiveSizeBits
4454 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4455 Res);
4456 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4457 Oversized = Res;
4458 return QualType();
4459 }
4460
4461 return Context.getConstantArrayType(VLATy->getElementType(),
4462 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00004463}
4464
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004465static void
4466FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie39e6ab42013-02-18 22:06:02 +00004467 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4468 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4469 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4470 DstPTL.getPointeeLoc());
4471 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004472 return;
4473 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004474 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4475 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4476 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4477 DstPTL.getInnerLoc());
4478 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4479 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004480 return;
4481 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004482 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4483 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4484 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4485 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004486 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie39e6ab42013-02-18 22:06:02 +00004487 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4488 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4489 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004490}
4491
Abramo Bagnara88adb982012-11-08 16:27:30 +00004492/// Helper method to turn variable array types into constant array
4493/// types in certain situations which would otherwise be errors (for
4494/// GCC compatibility).
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004495static TypeSourceInfo*
4496TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4497 ASTContext &Context,
4498 bool &SizeIsNegative,
4499 llvm::APSInt &Oversized) {
4500 QualType FixedTy
4501 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4502 SizeIsNegative, Oversized);
4503 if (FixedTy.isNull())
4504 return 0;
4505 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4506 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4507 FixedTInfo->getTypeLoc());
4508 return FixedTInfo;
4509}
4510
Richard Smith5ea6ef42013-01-10 23:43:47 +00004511/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith662f41b2013-06-18 20:15:12 +00004512/// that it can be found later for redeclarations. We include any extern "C"
4513/// declaration that is not visible in the translation unit here, not just
4514/// function-scope declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004515void
Richard Smith662f41b2013-06-18 20:15:12 +00004516Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithaa4bc182013-06-30 09:48:50 +00004517 if (!getLangOpts().CPlusPlus &&
4518 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4519 // Don't need to track declarations in the TU in C.
4520 return;
4521
Douglas Gregor63935192009-03-02 00:19:53 +00004522 // Note that we have a locally-scoped external with this name.
Richard Smithaa4bc182013-06-30 09:48:50 +00004523 // FIXME: There can be multiple such declarations if they are functions marked
4524 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith5ea6ef42013-01-10 23:43:47 +00004525 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor63935192009-03-02 00:19:53 +00004526}
4527
Richard Smith662f41b2013-06-18 20:15:12 +00004528NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregorec12ce22011-07-28 14:20:37 +00004529 if (ExternalSource) {
4530 // Load locally-scoped external decls from the external source.
Richard Smith662f41b2013-06-18 20:15:12 +00004531 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregorec12ce22011-07-28 14:20:37 +00004532 SmallVector<NamedDecl *, 4> Decls;
Richard Smith5ea6ef42013-01-10 23:43:47 +00004533 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregorec12ce22011-07-28 14:20:37 +00004534 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4535 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith5ea6ef42013-01-10 23:43:47 +00004536 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4537 if (Pos == LocallyScopedExternCDecls.end())
4538 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregorec12ce22011-07-28 14:20:37 +00004539 }
4540 }
Richard Smith662f41b2013-06-18 20:15:12 +00004541
4542 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola87bcee82013-10-19 16:55:03 +00004543 return D ? D->getMostRecentDecl() : 0;
Douglas Gregorec12ce22011-07-28 14:20:37 +00004544}
4545
Eli Friedman85a53192009-04-07 19:37:57 +00004546/// \brief Diagnose function specifiers on a declaration of an identifier that
4547/// does not identify a function.
Richard Smithc7f81162013-03-18 22:52:47 +00004548void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman85a53192009-04-07 19:37:57 +00004549 // FIXME: We should probably indicate the identifier in question to avoid
4550 // confusion for constructs like "inline int a(), b;"
Richard Smithc7f81162013-03-18 22:52:47 +00004551 if (DS.isInlineSpecified())
4552 Diag(DS.getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004553 diag::err_inline_non_function);
4554
Richard Smithc7f81162013-03-18 22:52:47 +00004555 if (DS.isVirtualSpecified())
4556 Diag(DS.getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004557 diag::err_virtual_non_function);
4558
Richard Smithc7f81162013-03-18 22:52:47 +00004559 if (DS.isExplicitSpecified())
4560 Diag(DS.getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004561 diag::err_explicit_non_function);
Richard Smithde03c152013-01-17 22:16:11 +00004562
Richard Smithc7f81162013-03-18 22:52:47 +00004563 if (DS.isNoreturnSpecified())
4564 Diag(DS.getNoreturnSpecLoc(),
Richard Smithde03c152013-01-17 22:16:11 +00004565 diag::err_noreturn_non_function);
Eli Friedman85a53192009-04-07 19:37:57 +00004566}
4567
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004568NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004569Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004570 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004571 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4572 if (D.getCXXScopeSpec().isSet()) {
4573 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4574 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004575 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004576 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00004577 DC = CurContext;
4578 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004579 }
4580
Richard Smithc7f81162013-03-18 22:52:47 +00004581 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +00004582
Richard Smithaf1fc7a2011-08-15 21:04:07 +00004583 if (D.getDeclSpec().isConstexprSpecified())
4584 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4585 << 1;
Eli Friedman63054b32009-04-19 20:27:55 +00004586
Douglas Gregoraef01992010-07-13 06:37:01 +00004587 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4588 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4589 << D.getName().getSourceRange();
4590 return 0;
4591 }
4592
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004593 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004594 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004595
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004596 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004597 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00004598
Richard Smith3e4c6c42011-05-05 21:57:07 +00004599 CheckTypedefForVariablyModifiedType(S, NewTD);
4600
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004601 bool Redeclaration = D.isRedeclaration();
4602 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4603 D.setRedeclaration(Redeclaration);
4604 return ND;
Richard Smith162e1c12011-04-15 14:24:37 +00004605}
4606
Richard Smith3e4c6c42011-05-05 21:57:07 +00004607void
4608Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004609 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4610 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004611 // Note that variably modified types must be fixed before merging the decl so
4612 // that redeclarations will match.
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004613 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4614 QualType T = TInfo->getType();
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004615 if (T->isVariablyModifiedType()) {
John McCall781472f2010-08-25 08:40:02 +00004616 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004617
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004618 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004619 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004620 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004621 TypeSourceInfo *FixedTInfo =
4622 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4623 SizeIsNegative,
4624 Oversized);
4625 if (FixedTInfo) {
Richard Smith162e1c12011-04-15 14:24:37 +00004626 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004627 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedman1ca48132009-02-21 00:44:51 +00004628 } else {
4629 if (SizeIsNegative)
Richard Smith162e1c12011-04-15 14:24:37 +00004630 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00004631 else if (T->isVariableArrayType())
Richard Smith162e1c12011-04-15 14:24:37 +00004632 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00004633 else if (Oversized.getBoolValue())
David Blaikied662a792011-10-19 22:56:21 +00004634 Diag(NewTD->getLocation(), diag::err_array_too_large)
4635 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00004636 else
Richard Smith162e1c12011-04-15 14:24:37 +00004637 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004638 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00004639 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004640 }
4641 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00004642}
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004643
Richard Smith3e4c6c42011-05-05 21:57:07 +00004644
4645/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4646/// declares a typedef-name, either using the 'typedef' type specifier or via
4647/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4648NamedDecl*
4649Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4650 LookupResult &Previous, bool &Redeclaration) {
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004651 // Merge the decl with the existing one if appropriate. If the decl is
4652 // in an outer scope, it isn't the same thing.
Richard Smith3e4c6c42011-05-05 21:57:07 +00004653 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregorcc209452011-03-07 16:54:27 +00004654 /*ExplicitInstantiationOrSpecialization=*/false);
Douglas Gregor7dc80e12013-01-09 00:47:56 +00004655 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004656 if (!Previous.empty()) {
4657 Redeclaration = true;
Richard Smith162e1c12011-04-15 14:24:37 +00004658 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004659 }
4660
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004661 // If this is the C FILE type, notify the AST context.
4662 if (IdentifierInfo *II = NewTD->getIdentifier())
4663 if (!NewTD->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004664 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stump782fa302009-07-28 02:25:19 +00004665 if (II->isStr("FILE"))
4666 Context.setFILEDecl(NewTD);
4667 else if (II->isStr("jmp_buf"))
4668 Context.setjmp_bufDecl(NewTD);
4669 else if (II->isStr("sigjmp_buf"))
4670 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00004671 else if (II->isStr("ucontext_t"))
4672 Context.setucontext_tDecl(NewTD);
Mike Stump782fa302009-07-28 02:25:19 +00004673 }
4674
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004675 return NewTD;
4676}
4677
Douglas Gregor8f301052009-02-24 19:23:27 +00004678/// \brief Determines whether the given declaration is an out-of-scope
4679/// previous declaration.
4680///
4681/// This routine should be invoked when name lookup has found a
4682/// previous declaration (PrevDecl) that is not in the scope where a
4683/// new declaration by the same name is being introduced. If the new
4684/// declaration occurs in a local scope, previous declarations with
4685/// linkage may still be considered previous declarations (C99
4686/// 6.2.2p4-5, C++ [basic.link]p6).
4687///
4688/// \param PrevDecl the previous declaration found by name
4689/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00004690///
Douglas Gregor8f301052009-02-24 19:23:27 +00004691/// \param DC the context in which the new declaration is being
4692/// declared.
4693///
4694/// \returns true if PrevDecl is an out-of-scope previous declaration
4695/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00004696static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00004697isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4698 ASTContext &Context) {
4699 if (!PrevDecl)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004700 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004701
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004702 if (!PrevDecl->hasLinkage())
4703 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004704
David Blaikie4e4d0842012-03-11 07:00:24 +00004705 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor8f301052009-02-24 19:23:27 +00004706 // C++ [basic.link]p6:
4707 // If there is a visible declaration of an entity with linkage
4708 // having the same name and type, ignoring entities declared
4709 // outside the innermost enclosing namespace scope, the block
4710 // scope declaration declares that same entity and receives the
4711 // linkage of the previous declaration.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004712 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor8f301052009-02-24 19:23:27 +00004713 if (!OuterContext->isFunctionOrMethod())
4714 // This rule only applies to block-scope declarations.
4715 return false;
Douglas Gregor757c6002010-08-27 22:55:10 +00004716
4717 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4718 if (PrevOuterContext->isRecord())
4719 // We found a member function: ignore it.
4720 return false;
4721
4722 // Find the innermost enclosing namespace for the new and
4723 // previous declarations.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004724 OuterContext = OuterContext->getEnclosingNamespaceContext();
4725 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump1eb44332009-09-09 15:08:12 +00004726
Douglas Gregor757c6002010-08-27 22:55:10 +00004727 // The previous declaration is in a different namespace, so it
4728 // isn't the same function.
4729 if (!OuterContext->Equals(PrevOuterContext))
4730 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004731 }
4732
Douglas Gregor8f301052009-02-24 19:23:27 +00004733 return true;
4734}
4735
John McCallb6217662010-03-15 10:12:16 +00004736static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4737 CXXScopeSpec &SS = D.getCXXScopeSpec();
4738 if (!SS.isSet()) return;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00004739 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +00004740}
4741
John McCallf85e1932011-06-15 23:02:42 +00004742bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4743 QualType type = decl->getType();
4744 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4745 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4746 // Various kinds of declaration aren't allowed to be __autoreleasing.
4747 unsigned kind = -1U;
4748 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4749 if (var->hasAttr<BlocksAttr>())
4750 kind = 0; // __block
4751 else if (!var->hasLocalStorage())
4752 kind = 1; // global
4753 } else if (isa<ObjCIvarDecl>(decl)) {
4754 kind = 3; // ivar
4755 } else if (isa<FieldDecl>(decl)) {
4756 kind = 2; // field
4757 }
4758
4759 if (kind != -1U) {
4760 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4761 << kind;
4762 }
4763 } else if (lifetime == Qualifiers::OCL_None) {
4764 // Try to infer lifetime.
4765 if (!type->isObjCLifetimeType())
4766 return false;
4767
4768 lifetime = type->getObjCARCImplicitLifetime();
4769 type = Context.getLifetimeQualifiedType(type, lifetime);
4770 decl->setType(type);
4771 }
4772
4773 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4774 // Thread-local variables cannot have lifetime.
4775 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smith38afbc72013-04-13 02:43:54 +00004776 var->getTLSKind()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004777 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004778 << var->getType();
4779 return true;
4780 }
4781 }
4782
4783 return false;
4784}
4785
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004786static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4787 // 'weak' only applies to declarations with external linkage.
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004788 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004789 if (!ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004790 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4791 ND.dropAttr<WeakAttr>();
4792 }
4793 }
4794 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004795 if (ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004796 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4797 ND.dropAttr<WeakRefAttr>();
4798 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004799 }
Reid Klecknera7225342013-05-20 14:02:37 +00004800
4801 // 'selectany' only applies to externally visible varable declarations.
4802 // It does not apply to functions.
4803 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4804 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4805 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4806 ND.dropAttr<SelectAnyAttr>();
4807 }
4808 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004809}
4810
John McCallb421d922013-04-02 02:48:58 +00004811/// Given that we are within the definition of the given function,
4812/// will that definition behave like C99's 'inline', where the
4813/// definition is discarded except for optimization purposes?
4814static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4815 // Try to avoid calling GetGVALinkageForFunction.
4816
4817 // All cases of this require the 'inline' keyword.
4818 if (!FD->isInlined()) return false;
4819
4820 // This is only possible in C++ with the gnu_inline attribute.
4821 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4822 return false;
4823
4824 // Okay, go ahead and call the relatively-more-expensive function.
4825
4826#ifndef NDEBUG
4827 // AST quite reasonably asserts that it's working on a function
4828 // definition. We don't really have a way to tell it that we're
4829 // currently defining the function, so just lie to it in +Asserts
4830 // builds. This is an awful hack.
4831 FD->setLazyBody(1);
4832#endif
4833
4834 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4835
4836#ifndef NDEBUG
4837 FD->setLazyBody(0);
4838#endif
4839
4840 return isC99Inline;
4841}
4842
Richard Smithaa4bc182013-06-30 09:48:50 +00004843/// Determine whether a variable is extern "C" prior to attaching
4844/// an initializer. We can't just call isExternC() here, because that
4845/// will also compute and cache whether the declaration is externally
4846/// visible, which might change when we attach the initializer.
4847///
4848/// This can only be used if the declaration is known to not be a
4849/// redeclaration of an internal linkage declaration.
4850///
4851/// For instance:
4852///
4853/// auto x = []{};
4854///
4855/// Attaching the initializer here makes this declaration not externally
4856/// visible, because its type has internal linkage.
4857///
4858/// FIXME: This is a hack.
4859template<typename T>
4860static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4861 if (S.getLangOpts().CPlusPlus) {
4862 // In C++, the overloadable attribute negates the effects of extern "C".
4863 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4864 return false;
4865 }
4866 return D->isExternC();
4867}
4868
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004869static bool shouldConsiderLinkage(const VarDecl *VD) {
4870 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4871 if (DC->isFunctionOrMethod())
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004872 return VD->hasExternalStorage();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004873 if (DC->isFileContext())
4874 return true;
4875 if (DC->isRecord())
4876 return false;
4877 llvm_unreachable("Unexpected context");
4878}
4879
4880static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4881 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4882 if (DC->isFileContext() || DC->isFunctionOrMethod())
4883 return true;
4884 if (DC->isRecord())
4885 return false;
4886 llvm_unreachable("Unexpected context");
4887}
4888
Richard Smitha41c97a2013-09-20 01:15:31 +00004889/// Adjust the \c DeclContext for a function or variable that might be a
4890/// function-local external declaration.
4891bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4892 if (!DC->isFunctionOrMethod())
4893 return false;
4894
4895 // If this is a local extern function or variable declared within a function
4896 // template, don't add it into the enclosing namespace scope until it is
4897 // instantiated; it might have a dependent type right now.
4898 if (DC->isDependentContext())
4899 return true;
4900
4901 // C++11 [basic.link]p7:
4902 // When a block scope declaration of an entity with linkage is not found to
4903 // refer to some other declaration, then that entity is a member of the
4904 // innermost enclosing namespace.
4905 //
4906 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4907 // semantically-enclosing namespace, not a lexically-enclosing one.
4908 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4909 DC = DC->getParent();
4910 return true;
4911}
4912
Larisse Voufoef4579c2013-08-06 01:03:05 +00004913NamedDecl *
Chris Lattner16c5dea2010-10-10 18:16:20 +00004914Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004915 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufoef4579c2013-08-06 01:03:05 +00004916 MultiTemplateParamsArg TemplateParamLists,
4917 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004918 QualType R = TInfo->getType();
Abramo Bagnara25777432010-08-11 22:01:17 +00004919 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004920
Douglas Gregor16573fa2010-04-19 22:54:31 +00004921 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00004922 VarDecl::StorageClass SC =
4923 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Gouly19dbb202013-01-23 11:56:20 +00004924
Richard Smitha41c97a2013-09-20 01:15:31 +00004925 DeclContext *OriginalDC = DC;
4926 bool IsLocalExternDecl = SC == SC_Extern &&
4927 adjustContextForLocalExternDecl(DC);
4928
Richard Smithdf4cc0a2013-04-15 08:33:22 +00004929 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004930 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4931 // half array type (unless the cl_khr_fp16 extension is enabled).
4932 if (Context.getBaseElementType(R)->isHalfType()) {
4933 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4934 D.setInvalidType();
4935 }
4936 }
4937
Douglas Gregor16573fa2010-04-19 22:54:31 +00004938 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004939 // mutable can only appear on non-static class members, so it's always
4940 // an error here
4941 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004942 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004943 SC = SC_None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004944 }
John McCallb421d922013-04-02 02:48:58 +00004945
Richard Smith9109bf12013-06-17 01:34:01 +00004946 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4947 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4948 D.getDeclSpec().getStorageClassSpecLoc())) {
4949 // In C++11, the 'register' storage class specifier is deprecated.
4950 // Suppress the warning in system macros, it's used in macros in some
4951 // popular C system headers, such as in glibc's htonl() macro.
4952 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4953 diag::warn_deprecated_register)
4954 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4955 }
4956
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004957 IdentifierInfo *II = Name.getAsIdentifierInfo();
4958 if (!II) {
4959 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorb5a01872011-10-09 18:55:59 +00004960 << Name;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004961 return 0;
4962 }
4963
Richard Smithc7f81162013-03-18 22:52:47 +00004964 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor021c3b32009-03-11 23:00:04 +00004965
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00004966 if (!DC->isRecord() && S->getFnParent() == 0) {
4967 // C99 6.9p2: The storage-class specifiers auto and register shall not
4968 // appear in the declaration specifiers in an external declaration.
John McCalld931b082010-08-26 03:08:43 +00004969 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004970 // If this is a register variable with an asm label specified, then this
4971 // is a GNU extension.
John McCalld931b082010-08-26 03:08:43 +00004972 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004973 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4974 else
4975 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004976 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004977 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004978 }
Richard Smith9109bf12013-06-17 01:34:01 +00004979
David Blaikie4e4d0842012-03-11 07:00:24 +00004980 if (getLangOpts().OpenCL) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004981 // Set up the special work-group-local storage class for variables in the
4982 // OpenCL __local address space.
Rafael Espindola0db661e2012-12-21 01:21:33 +00004983 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004984 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola0db661e2012-12-21 01:21:33 +00004985 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00004986
Guy Benyei21f18c42013-02-07 10:55:47 +00004987 // OpenCL v1.2 s6.9.b p4:
4988 // The sampler type cannot be used with the __local and __global address
4989 // space qualifiers.
4990 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
4991 R.getAddressSpace() == LangAS::opencl_global)) {
4992 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
4993 }
4994
Guy Benyeie6b9d802013-01-20 12:31:11 +00004995 // OpenCL 1.2 spec, p6.9 r:
4996 // The event type cannot be used to declare a program scope variable.
4997 // The event type cannot be used with the __local, __constant and __global
4998 // address space qualifiers.
4999 if (R->isEventT()) {
5000 if (S->getParent() == 0) {
5001 Diag(D.getLocStart(), diag::err_event_t_global_var);
5002 D.setInvalidType();
5003 }
5004
5005 if (R.getAddressSpace()) {
5006 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5007 D.setInvalidType();
5008 }
5009 }
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005010 }
5011
Larisse Voufoef4579c2013-08-06 01:03:05 +00005012 bool IsExplicitSpecialization = false;
5013 bool IsVariableTemplateSpecialization = false;
5014 bool IsPartialSpecialization = false;
Larisse Voufo4a919892013-08-14 03:09:19 +00005015 bool IsVariableTemplate = false;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005016 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo567f9172013-08-22 00:59:14 +00005017 VarDecl *NewVD = 0;
5018 VarTemplateDecl *NewTemplate = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00005019 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005020 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005021 D.getIdentifierLoc(), II,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005022 R, TInfo, SC);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005023
5024 if (D.isInvalidType())
5025 NewVD->setInvalidDecl();
5026 } else {
Larisse Voufo567f9172013-08-22 00:59:14 +00005027 bool Invalid = false;
5028
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005029 if (DC->isRecord() && !CurContext->isRecord()) {
5030 // This is an out-of-line definition of a static data member.
Rafael Espindola3882aed2013-06-19 13:41:54 +00005031 switch (SC) {
5032 case SC_None:
5033 break;
5034 case SC_Static:
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005035 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5036 diag::err_static_out_of_line)
5037 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola3882aed2013-06-19 13:41:54 +00005038 break;
5039 case SC_Auto:
5040 case SC_Register:
5041 case SC_Extern:
5042 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5043 // to names of variables declared in a block or to function parameters.
5044 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5045 // of class members
5046
5047 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5048 diag::err_storage_class_for_static_member)
5049 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5050 break;
5051 case SC_PrivateExtern:
5052 llvm_unreachable("C storage class in c++!");
5053 case SC_OpenCLWorkGroupLocal:
5054 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindolaea4b1112013-04-04 21:21:25 +00005055 }
Larisse Voufo06935f32013-08-06 03:43:07 +00005056 }
5057
Richard Smithb9c64d82012-02-16 20:41:22 +00005058 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005059 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5060 if (RD->isLocalClass())
5061 Diag(D.getIdentifierLoc(),
5062 diag::err_static_data_member_not_allowed_in_local_class)
5063 << Name << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00005064
Richard Smithb9c64d82012-02-16 20:41:22 +00005065 // C++98 [class.union]p1: If a union contains a static data member,
5066 // the program is ill-formed. C++11 drops this restriction.
5067 if (RD->isUnion())
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005068 Diag(D.getIdentifierLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005069 getLangOpts().CPlusPlus11
Richard Smithb9c64d82012-02-16 20:41:22 +00005070 ? diag::warn_cxx98_compat_static_data_member_in_union
5071 : diag::ext_static_data_member_in_union) << Name;
5072 // We conservatively disallow static data members in anonymous structs.
5073 else if (!RD->getDeclName())
5074 Diag(D.getIdentifierLoc(),
5075 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005076 << Name << RD->isUnion();
5077 }
5078 }
5079
Larisse Voufoef4579c2013-08-06 01:03:05 +00005080 NamedDecl *PrevDecl = 0;
5081 if (Previous.begin() != Previous.end())
5082 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5083 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5084
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005085 // Match up the template parameter lists with the scope specifier, then
5086 // determine whether we have a template or a template specialization.
Larisse Voufo567f9172013-08-22 00:59:14 +00005087 TemplateParameterList *TemplateParams =
5088 MatchTemplateParametersToScopeSpecifier(
5089 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5090 D.getCXXScopeSpec(), TemplateParamLists,
5091 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufoef4579c2013-08-06 01:03:05 +00005092 if (TemplateParams) {
5093 if (!TemplateParams->size() &&
5094 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005095 // There is an extraneous 'template<>' for this variable. Complain
5096 // about it, but allow the declaration of the variable.
5097 Diag(TemplateParams->getTemplateLoc(),
5098 diag::err_template_variable_noparams)
5099 << II
5100 << SourceRange(TemplateParams->getTemplateLoc(),
5101 TemplateParams->getRAngleLoc());
Larisse Voufoef4579c2013-08-06 01:03:05 +00005102 } else {
5103 // Only C++1y supports variable templates (N3651).
5104 Diag(D.getIdentifierLoc(),
5105 getLangOpts().CPlusPlus1y
5106 ? diag::warn_cxx11_compat_variable_template
5107 : diag::ext_variable_template);
5108
5109 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5110 // This is an explicit specialization or a partial specialization.
5111 // Check that we can declare a specialization here
5112
5113 IsVariableTemplateSpecialization = true;
5114 IsPartialSpecialization = TemplateParams->size() > 0;
5115
5116 } else { // if (TemplateParams->size() > 0)
Larisse Voufo06935f32013-08-06 03:43:07 +00005117 // This is a template declaration.
Larisse Voufo4a919892013-08-14 03:09:19 +00005118 IsVariableTemplate = true;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005119
5120 // Check that we can declare a template here.
5121 if (CheckTemplateDeclScope(S, TemplateParams))
5122 return 0;
5123
5124 // If there is a previous declaration with the same name, check
5125 // whether this is a valid redeclaration.
5126 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5127 PrevDecl = PrevVarTemplate = 0;
5128
5129 if (PrevVarTemplate) {
5130 // Ensure that the template parameter lists are compatible.
5131 if (!TemplateParameterListsAreEqual(
5132 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5133 /*Complain=*/true, TPL_TemplateMatch))
5134 return 0;
5135 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5136 // Maybe we will complain about the shadowed template parameter.
5137 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5138
5139 // Just pretend that we didn't see the previous declaration.
5140 PrevDecl = 0;
5141 } else if (PrevDecl) {
5142 // C++ [temp]p5:
5143 // ... a template name declared in namespace scope or in class
5144 // scope shall be unique in that scope.
5145 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5146 << Name;
5147 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5148 return 0;
5149 }
5150
5151 // Check the template parameter list of this declaration, possibly
5152 // merging in the template parameter list from the previous variable
5153 // template declaration.
5154 if (CheckTemplateParameterList(
5155 TemplateParams,
5156 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5157 : 0,
5158 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5159 DC->isDependentContext())
5160 ? TPC_ClassTemplateMember
5161 : TPC_VarTemplate))
5162 Invalid = true;
5163
5164 if (D.getCXXScopeSpec().isSet()) {
5165 // If the name of the template was qualified, we must be defining
5166 // the template out-of-line.
5167 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5168 !PrevVarTemplate) {
Richard Smith4e9686b2013-08-09 04:35:01 +00005169 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5170 << Name << DC << /*IsDefinition*/true
5171 << D.getCXXScopeSpec().getRange();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005172 Invalid = true;
5173 }
5174 }
5175 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005176 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00005177 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5178 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5179
5180 // We have encountered something that the user meant to be a
5181 // specialization (because it has explicitly-specified template
5182 // arguments) but that was not introduced with a "template<>" (or had
5183 // too few of them).
5184 // FIXME: Differentiate between attempts for explicit instantiations
5185 // (starting with "template") and the rest.
5186 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5187 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5188 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5189 "template<> ");
5190 IsVariableTemplateSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00005191 }
Mike Stump1eb44332009-09-09 15:08:12 +00005192
Larisse Voufoef4579c2013-08-06 01:03:05 +00005193 if (IsVariableTemplateSpecialization) {
5194 if (!PrevVarTemplate) {
5195 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5196 << IsPartialSpecialization;
5197 return 0;
5198 }
5199
5200 SourceLocation TemplateKWLoc =
5201 TemplateParamLists.size() > 0
5202 ? TemplateParamLists[0]->getTemplateLoc()
5203 : SourceLocation();
5204 DeclResult Res = ActOnVarTemplateSpecialization(
5205 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5206 IsPartialSpecialization);
5207 if (Res.isInvalid())
5208 return 0;
5209 NewVD = cast<VarDecl>(Res.get());
5210 AddToScope = false;
5211 } else
5212 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5213 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedman63054b32009-04-19 20:27:55 +00005214
Larisse Voufo567f9172013-08-22 00:59:14 +00005215 // If this is supposed to be a variable template, create it as such.
5216 if (IsVariableTemplate) {
5217 NewTemplate =
5218 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5219 TemplateParams, NewVD, PrevVarTemplate);
5220 NewVD->setDescribedVarTemplate(NewTemplate);
5221 }
5222
Richard Smith483b9f32011-02-21 20:05:19 +00005223 // If this decl has an auto type in need of deduction, make a note of the
5224 // Decl so we can diagnose uses of it in its own initializer.
Richard Smitha2c36462013-04-26 16:15:35 +00005225 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smith483b9f32011-02-21 20:05:19 +00005226 ParsingInitForAutoVars.insert(NewVD);
Richard Smith34b41d92011-02-20 03:19:35 +00005227
Larisse Voufo567f9172013-08-22 00:59:14 +00005228 if (D.isInvalidType() || Invalid) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005229 NewVD->setInvalidDecl();
Larisse Voufo567f9172013-08-22 00:59:14 +00005230 if (NewTemplate)
5231 NewTemplate->setInvalidDecl();
5232 }
Mike Stump1eb44332009-09-09 15:08:12 +00005233
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005234 SetNestedNameSpecifier(NewVD, D);
John McCallb6217662010-03-15 10:12:16 +00005235
Larisse Voufoef4579c2013-08-06 01:03:05 +00005236 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5237 if (TemplateParams && TemplateParamLists.size() > 1 &&
5238 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5239 NewVD->setTemplateParameterListsInfo(
5240 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5241 } else if (IsVariableTemplateSpecialization ||
5242 (!TemplateParams && TemplateParamLists.size() > 0 &&
5243 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005244 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005245 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00005246 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005247 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005248
Richard Smith7ca48502012-02-13 22:16:19 +00005249 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithdd4b3502011-12-25 21:17:58 +00005250 NewVD->setConstexpr(true);
Abramo Bagnara9b934882010-06-12 08:15:14 +00005251 }
5252
Douglas Gregore3895852011-09-12 18:37:38 +00005253 // Set the lexical context. If the declarator has a C++ scope specifier, the
5254 // lexical context will be different from the semantic context.
5255 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo567f9172013-08-22 00:59:14 +00005256 if (NewTemplate)
5257 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregore3895852011-09-12 18:37:38 +00005258
Richard Smitha41c97a2013-09-20 01:15:31 +00005259 if (IsLocalExternDecl)
5260 NewVD->setLocalExternDecl();
5261
Richard Smithec642442013-04-12 22:46:28 +00005262 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005263 if (NewVD->hasLocalStorage()) {
5264 // C++11 [dcl.stc]p4:
5265 // When thread_local is applied to a variable of block scope the
5266 // storage-class-specifier static is implied if it does not appear
5267 // explicitly.
5268 // Core issue: 'static' is not implied if the variable is declared
5269 // 'extern'.
5270 if (SCSpec == DeclSpec::SCS_unspecified &&
5271 TSCS == DeclSpec::TSCS_thread_local &&
5272 DC->isFunctionOrMethod())
5273 NewVD->setTSCSpec(TSCS);
5274 else
5275 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5276 diag::err_thread_non_global)
5277 << DeclSpec::getSpecifierName(TSCS);
5278 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithec642442013-04-12 22:46:28 +00005279 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5280 diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00005281 else
Enea Zaffanelladc173842013-05-04 08:27:07 +00005282 NewVD->setTSCSpec(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00005283 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005284
John McCallb421d922013-04-02 02:48:58 +00005285 // C99 6.7.4p3
5286 // An inline definition of a function with external linkage shall
5287 // not contain a definition of a modifiable object with static or
5288 // thread storage duration...
5289 // We only apply this when the function is required to be defined
5290 // elsewhere, i.e. when the function is not 'extern inline'. Note
5291 // that a local variable with thread storage duration still has to
5292 // be marked 'static'. Also note that it's possible to get these
5293 // semantics in C++ using __attribute__((gnu_inline)).
5294 if (SC == SC_Static && S->getFnParent() != 0 &&
5295 !NewVD->getType().isConstQualified()) {
5296 FunctionDecl *CurFD = getCurFunctionDecl();
5297 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5298 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5299 diag::warn_static_local_in_extern_inline);
5300 MaybeSuggestAddingStaticToDecl(CurFD);
5301 }
5302 }
5303
Douglas Gregord023aec2011-09-09 20:53:38 +00005304 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00005305 if (IsVariableTemplateSpecialization)
5306 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5307 << (IsPartialSpecialization ? 1 : 0)
5308 << FixItHint::CreateRemoval(
5309 D.getDeclSpec().getModulePrivateSpecLoc());
5310 else if (IsExplicitSpecialization)
Douglas Gregord023aec2011-09-09 20:53:38 +00005311 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5312 << 2
5313 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregore3895852011-09-12 18:37:38 +00005314 else if (NewVD->hasLocalStorage())
5315 Diag(NewVD->getLocation(), diag::err_module_private_local)
5316 << 0 << NewVD->getDeclName()
5317 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5318 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo567f9172013-08-22 00:59:14 +00005319 else {
Douglas Gregord023aec2011-09-09 20:53:38 +00005320 NewVD->setModulePrivate();
Larisse Voufo567f9172013-08-22 00:59:14 +00005321 if (NewTemplate)
5322 NewTemplate->setModulePrivate();
5323 }
Douglas Gregord023aec2011-09-09 20:53:38 +00005324 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00005325
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005326 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005327 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005328
Richard Smithbe507b62013-02-01 08:12:08 +00005329 if (NewVD->hasAttrs())
5330 CheckAlignasUnderalignment(NewVD);
5331
Peter Collingbournec0c00662012-08-28 20:37:50 +00005332 if (getLangOpts().CUDA) {
5333 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5334 // storage [duration]."
5335 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola0db661e2012-12-21 01:21:33 +00005336 (NewVD->hasAttr<CUDASharedAttr>() ||
5337 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec0c00662012-08-28 20:37:50 +00005338 NewVD->setStorageClass(SC_Static);
Rafael Espindola0db661e2012-12-21 01:21:33 +00005339 }
Peter Collingbournec0c00662012-08-28 20:37:50 +00005340 }
5341
John McCallf85e1932011-06-15 23:02:42 +00005342 // In auto-retain/release, infer strong retension for variables of
5343 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00005344 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCallf85e1932011-06-15 23:02:42 +00005345 NewVD->setInvalidDecl();
5346
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005347 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner16c5dea2010-10-10 18:16:20 +00005348 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005349 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00005350 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner5f9e2722011-07-23 10:55:15 +00005351 StringRef Label = SE->getString();
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005352 if (S->getFnParent() != 0) {
5353 switch (SC) {
5354 case SC_None:
5355 case SC_Auto:
5356 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5357 break;
5358 case SC_Register:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00005359 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005360 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5361 break;
5362 case SC_Static:
5363 case SC_Extern:
5364 case SC_PrivateExtern:
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005365 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005366 break;
5367 }
5368 }
5369
5370 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindolabaf86952011-01-01 21:47:03 +00005371 Context, Label));
David Chisnall5f3c1632012-02-18 16:12:34 +00005372 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5373 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5374 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5375 if (I != ExtnameUndeclaredIdentifiers.end()) {
5376 NewVD->addAttr(I->second);
5377 ExtnameUndeclaredIdentifiers.erase(I);
5378 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005379 }
5380
John McCall8472af42010-03-16 21:48:18 +00005381 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00005382 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00005383 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00005384
John McCall68263142009-11-18 22:49:29 +00005385 // Don't consider existing declarations that are in a different
5386 // scope and are out-of-semantic-context declarations (if the new
5387 // declaration has linkage).
Larisse Voufoef4579c2013-08-06 01:03:05 +00005388 FilterLookupForScope(
Richard Smitha41c97a2013-09-20 01:15:31 +00005389 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
Larisse Voufoef4579c2013-08-06 01:03:05 +00005390 IsExplicitSpecialization || IsVariableTemplateSpecialization);
5391
Richard Smithdd9459f2013-08-13 18:18:50 +00005392 // Check whether the previous declaration is in the same block scope. This
5393 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5394 if (getLangOpts().CPlusPlus &&
5395 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5396 NewVD->setPreviousDeclInSameBlockScope(
5397 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00005398 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smithdd9459f2013-08-13 18:18:50 +00005399
David Blaikie4e4d0842012-03-11 07:00:24 +00005400 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005401 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5402 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005403 // Merge the decl with the existing one if appropriate.
5404 if (!Previous.empty()) {
5405 if (Previous.isSingleResult() &&
5406 isa<FieldDecl>(Previous.getFoundDecl()) &&
5407 D.getCXXScopeSpec().isSet()) {
5408 // The user tried to define a non-static data member
5409 // out-of-line (C++ [dcl.meaning]p1).
5410 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5411 << D.getCXXScopeSpec().getRange();
5412 Previous.clear();
5413 NewVD->setInvalidDecl();
5414 }
5415 } else if (D.getCXXScopeSpec().isSet()) {
5416 // No previous declaration in the qualifying scope.
5417 Diag(D.getIdentifierLoc(), diag::err_no_member)
5418 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005419 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005420 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005421 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005422
Larisse Voufoef4579c2013-08-06 01:03:05 +00005423 if (!IsVariableTemplateSpecialization) {
5424 if (PrevVarTemplate) {
5425 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5426 LookupOrdinaryName, ForRedeclaration);
5427 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo567f9172013-08-22 00:59:14 +00005428 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005429 } else
Larisse Voufo567f9172013-08-22 00:59:14 +00005430 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005431 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005432
5433 // This is an explicit specialization of a static data member. Check it.
Larisse Voufoef4579c2013-08-06 01:03:05 +00005434 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005435 CheckMemberSpecialization(NewVD, Previous))
5436 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005437 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00005438
Rafael Espindola65611bf2013-03-02 21:41:48 +00005439 ProcessPragmaWeak(S, NewVD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00005440 checkAttributesAfterMerging(*this, *NewVD);
5441
Richard Smithaa4bc182013-06-30 09:48:50 +00005442 // If this is the first declaration of an extern C variable, update
5443 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00005444 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00005445 isIncompleteDeclExternC(*this, NewVD))
Richard Smith662f41b2013-06-18 20:15:12 +00005446 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005447
Reid Kleckner942f9fe2013-09-10 20:14:30 +00005448 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman5e867c82013-07-10 00:30:46 +00005449 Decl *ManglingContextDecl;
5450 if (MangleNumberingContext *MCtx =
5451 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5452 ManglingContextDecl)) {
5453 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5454 }
5455 }
5456
Larisse Voufoef4579c2013-08-06 01:03:05 +00005457 // If we are providing an explicit specialization of a static variable
5458 // template, make a note of that.
5459 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo04592e72013-08-22 00:28:27 +00005460 PrevVarTemplate->setMemberSpecialization();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005461
Larisse Voufo567f9172013-08-22 00:59:14 +00005462 if (NewTemplate) {
5463 ActOnDocumentableDecl(NewTemplate);
5464 return NewTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005465 }
5466
Larisse Voufo567f9172013-08-22 00:59:14 +00005467 return NewVD;
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005468}
5469
John McCall053f4bd2010-03-22 09:20:08 +00005470/// \brief Diagnose variable or built-in function shadowing. Implements
5471/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00005472///
John McCall053f4bd2010-03-22 09:20:08 +00005473/// This method is called whenever a VarDecl is added to a "useful"
5474/// scope.
John McCall8472af42010-03-16 21:48:18 +00005475///
John McCalla369a952010-03-20 04:12:52 +00005476/// \param S the scope in which the shadowing name is being declared
5477/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00005478///
John McCall053f4bd2010-03-22 09:20:08 +00005479void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00005480 // Return if warning is ignored.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005481 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005482 DiagnosticsEngine::Ignored)
John McCall8472af42010-03-16 21:48:18 +00005483 return;
5484
Argyrios Kyrtzidis651f86f2011-02-08 18:21:25 +00005485 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005486 if (D->hasGlobalStorage())
John McCall8472af42010-03-16 21:48:18 +00005487 return;
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005488
5489 DeclContext *NewDC = D->getDeclContext();
5490
John McCalla369a952010-03-20 04:12:52 +00005491 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00005492 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00005493 return;
John McCall8472af42010-03-16 21:48:18 +00005494
John McCall8472af42010-03-16 21:48:18 +00005495 NamedDecl* ShadowedDecl = R.getFoundDecl();
5496 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5497 return;
5498
Argyrios Kyrtzidis36eb5e42011-01-31 07:04:54 +00005499 // Fields are not shadowed by variables in C++ static methods.
5500 if (isa<FieldDecl>(ShadowedDecl))
5501 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5502 if (MD->isStatic())
5503 return;
5504
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005505 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5506 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005507 // For shadowing external vars, make sure that we point to the global
5508 // declaration, not a locally scoped extern declaration.
5509 for (VarDecl::redecl_iterator
5510 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5511 I != E; ++I)
5512 if (I->isFileVarDecl()) {
5513 ShadowedDecl = *I;
5514 break;
5515 }
5516 }
5517
5518 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5519
John McCalla369a952010-03-20 04:12:52 +00005520 // Only warn about certain kinds of shadowing for class members.
5521 if (NewDC && NewDC->isRecord()) {
5522 // In particular, don't warn about shadowing non-class members.
5523 if (!OldDC->isRecord())
5524 return;
5525
5526 // TODO: should we warn about static data members shadowing
5527 // static data members from base classes?
5528
5529 // TODO: don't diagnose for inaccessible shadowed members.
5530 // This is hard to do perfectly because we might friend the
5531 // shadowing context, but that's just a false negative.
5532 }
5533
5534 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00005535 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00005536 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00005537 if (isa<FieldDecl>(ShadowedDecl))
5538 Kind = 3; // field
5539 else
5540 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00005541 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00005542 Kind = 1; // global
5543 else
5544 Kind = 0; // local
5545
John McCalla369a952010-03-20 04:12:52 +00005546 DeclarationName Name = R.getLookupName();
5547
John McCall8472af42010-03-16 21:48:18 +00005548 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00005549 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00005550 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5551}
5552
John McCall053f4bd2010-03-22 09:20:08 +00005553/// \brief Check -Wshadow without the advantage of a previous lookup.
5554void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005555 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005556 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005557 return;
5558
John McCall053f4bd2010-03-22 09:20:08 +00005559 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5560 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5561 LookupName(R, S);
5562 CheckShadow(S, D, R);
5563}
5564
Richard Smithaa4bc182013-06-30 09:48:50 +00005565/// Check for conflict between this global or extern "C" declaration and
5566/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola294ddc62013-01-11 19:34:23 +00005567template<typename T>
Richard Smithaa4bc182013-06-30 09:48:50 +00005568static bool checkGlobalOrExternCConflict(
5569 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5570 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5571 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005572
Richard Smithaa4bc182013-06-30 09:48:50 +00005573 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5574 // The common case: this global doesn't conflict with any extern "C"
5575 // declaration.
5576 return false;
5577 }
5578
5579 if (Prev) {
5580 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5581 // Both the old and new declarations have C language linkage. This is a
5582 // redeclaration.
5583 Previous.clear();
5584 Previous.addDecl(Prev);
5585 return true;
5586 }
5587
5588 // This is a global, non-extern "C" declaration, and there is a previous
5589 // non-global extern "C" declaration. Diagnose if this is a variable
5590 // declaration.
5591 if (!isa<VarDecl>(ND))
5592 return false;
5593 } else {
5594 // The declaration is extern "C". Check for any declaration in the
5595 // translation unit which might conflict.
5596 if (IsGlobal) {
5597 // We have already performed the lookup into the translation unit.
5598 IsGlobal = false;
5599 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5600 I != E; ++I) {
5601 if (isa<VarDecl>(*I)) {
5602 Prev = *I;
5603 break;
5604 }
5605 }
5606 } else {
5607 DeclContext::lookup_result R =
5608 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5609 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5610 I != E; ++I) {
5611 if (isa<VarDecl>(*I)) {
5612 Prev = *I;
5613 break;
5614 }
5615 // FIXME: If we have any other entity with this name in global scope,
5616 // the declaration is ill-formed, but that is a defect: it breaks the
5617 // 'stat' hack, for instance. Only variables can have mangled name
5618 // clashes with extern "C" declarations, so only they deserve a
5619 // diagnostic.
5620 }
5621 }
5622
5623 if (!Prev)
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005624 return false;
5625 }
5626
Richard Smithaa4bc182013-06-30 09:48:50 +00005627 // Use the first declaration's location to ensure we point at something which
5628 // is lexically inside an extern "C" linkage-spec.
5629 assert(Prev && "should have found a previous declaration to diagnose");
5630 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindolabc650912013-10-17 15:37:26 +00005631 Prev = FD->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005632 else
Rafael Espindolabc650912013-10-17 15:37:26 +00005633 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005634
5635 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5636 << IsGlobal << ND;
5637 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5638 << IsGlobal;
5639 return false;
5640}
5641
5642/// Apply special rules for handling extern "C" declarations. Returns \c true
5643/// if we have found that this is a redeclaration of some prior entity.
5644///
5645/// Per C++ [dcl.link]p6:
5646/// Two declarations [for a function or variable] with C language linkage
5647/// with the same name that appear in different scopes refer to the same
5648/// [entity]. An entity with C language linkage shall not be declared with
5649/// the same name as an entity in global scope.
5650template<typename T>
5651static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5652 LookupResult &Previous) {
5653 if (!S.getLangOpts().CPlusPlus) {
5654 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smitha41c97a2013-09-20 01:15:31 +00005655 // variable declared in function scope. We don't need this in C++, because
5656 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithaa4bc182013-06-30 09:48:50 +00005657 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5658 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5659 Previous.clear();
5660 Previous.addDecl(Prev);
5661 return true;
5662 }
5663 }
5664 return false;
5665 }
5666
5667 // A declaration in the translation unit can conflict with an extern "C"
5668 // declaration.
5669 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5670 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5671
5672 // An extern "C" declaration can conflict with a declaration in the
5673 // translation unit or can be a redeclaration of an extern "C" declaration
5674 // in another scope.
5675 if (isIncompleteDeclExternC(S,ND))
5676 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5677
5678 // Neither global nor extern "C": nothing to do.
5679 return false;
Rafael Espindola294ddc62013-01-11 19:34:23 +00005680}
5681
Richard Smithdc7a4f52013-04-30 13:56:41 +00005682void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00005683 // If the decl is already known invalid, don't check it.
5684 if (NewVD->isInvalidDecl())
Richard Smithdc7a4f52013-04-30 13:56:41 +00005685 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005686
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005687 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5688 QualType T = TInfo->getType();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005689
Richard Smithdc7a4f52013-04-30 13:56:41 +00005690 // Defer checking an 'auto' type until its initializer is attached.
5691 if (T->isUndeducedType())
5692 return;
5693
John McCallc12c5bb2010-05-15 11:32:37 +00005694 if (T->isObjCObjectType()) {
Fariborz Jahaniandcf10112011-07-25 21:12:27 +00005695 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5696 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00005697 T = Context.getObjCObjectPointerType(T);
5698 NewVD->setType(T);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005699 }
Mike Stump1eb44332009-09-09 15:08:12 +00005700
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005701 // Emit an error if an address space was applied to decl with local storage.
5702 // This includes arrays of objects with address space qualifiers, but not
5703 // automatic variables that point to other address spaces.
5704 // ISO/IEC TR 18037 S5.1.2
Chris Lattner16c5dea2010-10-10 18:16:20 +00005705 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005706 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005707 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005708 return;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005709 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00005710
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005711 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5712 // __constant address space.
5713 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5714 && T.getAddressSpace() != LangAS::opencl_constant
5715 && !T->isSamplerT()){
5716 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5717 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005718 return;
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005719 }
5720
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005721 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5722 // scope.
5723 if ((getLangOpts().OpenCLVersion >= 120)
5724 && NewVD->isStaticLocal()) {
5725 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5726 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005727 return;
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005728 }
5729
Mike Stumpf33651c2009-04-14 00:57:29 +00005730 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanian175df892011-06-07 20:15:46 +00005731 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005732 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanian175df892011-06-07 20:15:46 +00005733 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005734 else {
5735 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanian175df892011-06-07 20:15:46 +00005736 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005737 }
Fariborz Jahanian175df892011-06-07 20:15:46 +00005738 }
Chris Lattner16c5dea2010-10-10 18:16:20 +00005739
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005740 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00005741 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00005742 NewVD->hasAttr<BlocksAttr>())
John McCall781472f2010-08-25 08:40:02 +00005743 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00005744
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005745 if ((isVM && NewVD->hasLinkage()) ||
5746 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005747 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00005748 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005749 TypeSourceInfo *FixedTInfo =
5750 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5751 SizeIsNegative, Oversized);
5752 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005753 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00005754 // FIXME: This won't give the correct result for
5755 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005756 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005757
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005758 if (NewVD->isFileVarDecl())
5759 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005760 << SizeRange;
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005761 else if (NewVD->isStaticLocal())
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005762 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005763 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005764 else
5765 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005766 << SizeRange;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005767 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005768 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005769 }
5770
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005771 if (FixedTInfo == 0) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005772 if (NewVD->isFileVarDecl())
5773 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5774 else
5775 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005776 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005777 return;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005778 }
Mike Stump1eb44332009-09-09 15:08:12 +00005779
Chris Lattnereaaebc72009-04-25 08:06:05 +00005780 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnaraeae859a2012-11-08 16:01:51 +00005781 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005782 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005783 }
5784
David Majnemeraa715672013-05-29 00:56:45 +00005785 if (T->isVoidType()) {
5786 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5787 // of objects and functions.
5788 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5789 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5790 << T;
5791 NewVD->setInvalidDecl();
5792 return;
5793 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00005794 }
5795
5796 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5797 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5798 NewVD->setInvalidDecl();
5799 return;
5800 }
5801
5802 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5803 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5804 NewVD->setInvalidDecl();
5805 return;
5806 }
5807
5808 if (NewVD->isConstexpr() && !T->isDependentType() &&
5809 RequireLiteralType(NewVD->getLocation(), T,
5810 diag::err_constexpr_var_non_literal)) {
5811 // Can't perform this check until the type is deduced.
5812 NewVD->setInvalidDecl();
5813 return;
5814 }
5815}
5816
5817/// \brief Perform semantic checking on a newly-created variable
5818/// declaration.
5819///
5820/// This routine performs all of the type-checking required for a
5821/// variable declaration once it has been built. It is used both to
5822/// check variables after they have been parsed and their declarators
5823/// have been translated into a declaration, and to check variables
5824/// that have been instantiated from a template.
5825///
5826/// Sets NewVD->isInvalidDecl() if an error was encountered.
5827///
5828/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo567f9172013-08-22 00:59:14 +00005829bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00005830 CheckVariableDeclarationType(NewVD);
5831
5832 // If the decl is already known invalid, don't check it.
5833 if (NewVD->isInvalidDecl())
5834 return false;
5835
John McCall5b8740f2013-04-01 18:34:28 +00005836 // If we did not find anything by this name, look for a non-visible
5837 // extern "C" declaration with the same name.
Richard Smithdd9459f2013-08-13 18:18:50 +00005838 if (Previous.empty() &&
5839 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith99a72382013-09-03 21:00:58 +00005840 Previous.setShadowed();
Douglas Gregor63935192009-03-02 00:19:53 +00005841
Douglas Gregor7dc80e12013-01-09 00:47:56 +00005842 // Filter out any non-conflicting previous declarations.
5843 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5844
John McCall68263142009-11-18 22:49:29 +00005845 if (!Previous.empty()) {
Richard Smith99a72382013-09-03 21:00:58 +00005846 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005847 return true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005848 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005849 return false;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005850}
5851
Douglas Gregora8f32e02009-10-06 17:59:45 +00005852/// \brief Data used with FindOverriddenMethod
5853struct FindOverriddenMethodData {
5854 Sema *S;
5855 CXXMethodDecl *Method;
5856};
5857
5858/// \brief Member lookup function that determines whether a given C++
5859/// method overrides a method in a base class, to be used with
5860/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00005861static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00005862 CXXBasePath &Path,
5863 void *UserData) {
5864 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00005865
Douglas Gregora8f32e02009-10-06 17:59:45 +00005866 FindOverriddenMethodData *Data
5867 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00005868
5869 DeclarationName Name = Data->Method->getDeclName();
5870
5871 // FIXME: Do we care about other names here too?
5872 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00005873 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00005874 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5875 CanQualType CT = Data->S->Context.getCanonicalType(T);
5876
Anders Carlsson1a689722009-11-27 01:26:58 +00005877 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00005878 }
5879
5880 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005881 !Path.Decls.empty();
5882 Path.Decls = Path.Decls.slice(1)) {
5883 NamedDecl *D = Path.Decls.front();
John McCallad00b772010-06-16 08:42:20 +00005884 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5885 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00005886 return true;
5887 }
5888 }
5889
5890 return false;
5891}
5892
David Blaikie5708c182012-10-17 00:47:58 +00005893namespace {
5894 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5895}
5896/// \brief Report an error regarding overriding, along with any relevant
5897/// overriden methods.
5898///
5899/// \param DiagID the primary error to report.
5900/// \param MD the overriding method.
5901/// \param OEK which overrides to include as notes.
5902static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5903 OverrideErrorKind OEK = OEK_All) {
5904 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5905 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5906 E = MD->end_overridden_methods();
5907 I != E; ++I) {
5908 // This check (& the OEK parameter) could be replaced by a predicate, but
5909 // without lambdas that would be overkill. This is still nicer than writing
5910 // out the diag loop 3 times.
5911 if ((OEK == OEK_All) ||
5912 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5913 (OEK == OEK_Deleted && (*I)->isDeleted()))
5914 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5915 }
5916}
5917
Sebastian Redla165da02009-11-18 21:51:29 +00005918/// AddOverriddenMethods - See if a method overrides any in the base classes,
5919/// and if so, check that it's a valid override and remember it.
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005920bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redla165da02009-11-18 21:51:29 +00005921 // Look for virtual methods in base classes that this method might override.
5922 CXXBasePaths Paths;
5923 FindOverriddenMethodData Data;
5924 Data.Method = MD;
5925 Data.S = this;
David Blaikie5708c182012-10-17 00:47:58 +00005926 bool hasDeletedOverridenMethods = false;
5927 bool hasNonDeletedOverridenMethods = false;
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005928 bool AddedAny = false;
Sebastian Redla165da02009-11-18 21:51:29 +00005929 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5930 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5931 E = Paths.found_decls_end(); I != E; ++I) {
5932 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu304e2332011-07-01 20:02:53 +00005933 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00005934 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballmanfff32482012-12-09 17:45:41 +00005935 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithb9d0b762012-07-27 04:22:15 +00005936 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson2e1c7302011-01-20 16:25:36 +00005937 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie5708c182012-10-17 00:47:58 +00005938 hasDeletedOverridenMethods |= OldMD->isDeleted();
5939 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005940 AddedAny = true;
5941 }
Sebastian Redla165da02009-11-18 21:51:29 +00005942 }
5943 }
5944 }
David Blaikie5708c182012-10-17 00:47:58 +00005945
5946 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5947 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5948 }
5949 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5950 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5951 }
5952
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005953 return AddedAny;
Sebastian Redla165da02009-11-18 21:51:29 +00005954}
5955
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005956namespace {
5957 // Struct for holding all of the extra arguments needed by
5958 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5959 struct ActOnFDArgs {
5960 Scope *S;
5961 Declarator &D;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005962 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005963 bool AddToScope;
5964 };
5965}
5966
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005967namespace {
5968
5969// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005970// Also only accept corrections that have the same parent decl.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005971class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5972 public:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005973 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5974 CXXRecordDecl *Parent)
5975 : Context(Context), OriginalFD(TypoFD),
5976 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005977
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005978 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005979 if (candidate.getEditDistance() == 0)
5980 return false;
5981
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005982 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005983 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5984 CDeclEnd = candidate.end();
5985 CDecl != CDeclEnd; ++CDecl) {
5986 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5987
5988 if (FD && !FD->hasBody() &&
5989 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
5990 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5991 CXXRecordDecl *Parent = MD->getParent();
5992 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
5993 return true;
5994 } else if (!ExpectedParent) {
5995 return true;
5996 }
5997 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005998 }
5999
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006000 return false;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006001 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006002
6003 private:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006004 ASTContext &Context;
6005 FunctionDecl *OriginalFD;
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006006 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006007};
6008
6009}
6010
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006011/// \brief Generate diagnostics for an invalid function redeclaration.
6012///
6013/// This routine handles generating the diagnostic messages for an invalid
6014/// function redeclaration, including finding possible similar declarations
6015/// or performing typo correction if there are no previous declarations with
6016/// the same name.
6017///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006018/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006019/// the new declaration name does not cause new errors.
Richard Smith4e9686b2013-08-09 04:35:01 +00006020static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006021 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith4e9686b2013-08-09 04:35:01 +00006022 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006023 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006024 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006025 SmallVector<unsigned, 1> MismatchedParams;
6026 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006027 TypoCorrection Correction;
Richard Smith2d670972013-08-17 00:46:16 +00006028 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith4e9686b2013-08-09 04:35:01 +00006029 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6030 : diag::err_member_decl_does_not_match;
6031 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6032 IsLocalFriend ? Sema::LookupLocalFriendName
6033 : Sema::LookupOrdinaryName,
6034 Sema::ForRedeclaration);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006035
6036 NewFD->setInvalidDecl();
Richard Smith4e9686b2013-08-09 04:35:01 +00006037 if (IsLocalFriend)
6038 SemaRef.LookupName(Prev, S);
6039 else
6040 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCall29ae6e52010-10-13 05:45:15 +00006041 assert(!Prev.isAmbiguous() &&
6042 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006043 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006044 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6045 MD ? MD->getParent() : 0);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006046 if (!Prev.empty()) {
6047 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6048 Func != FuncEnd; ++Func) {
6049 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006050 if (FD &&
6051 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006052 // Add 1 to the index so that 0 can mean the mismatch didn't
6053 // involve a parameter
6054 unsigned ParamNum =
6055 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6056 NearMatches.push_back(std::make_pair(FD, ParamNum));
6057 }
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00006058 }
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006059 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith4e9686b2013-08-09 04:35:01 +00006060 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smith2d670972013-08-17 00:46:16 +00006061 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6062 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6063 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006064 // Set up everything for the call to ActOnFunctionDeclarator
6065 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6066 ExtraArgs.D.getIdentifierLoc());
6067 Previous.clear();
6068 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006069 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6070 CDeclEnd = Correction.end();
6071 CDecl != CDeclEnd; ++CDecl) {
6072 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006073 if (FD && !FD->hasBody() &&
6074 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006075 Previous.addDecl(FD);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006076 }
6077 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006078 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smith2d670972013-08-17 00:46:16 +00006079
6080 NamedDecl *Result;
6081 // Retry building the function declaration with the new previous
6082 // declarations, and with errors suppressed.
6083 {
6084 // Trap errors.
6085 Sema::SFINAETrap Trap(SemaRef);
6086
6087 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6088 // pieces need to verify the typo-corrected C++ declaration and hopefully
6089 // eliminate the need for the parameter pack ExtraArgs.
6090 Result = SemaRef.ActOnFunctionDeclarator(
6091 ExtraArgs.S, ExtraArgs.D,
6092 Correction.getCorrectionDecl()->getDeclContext(),
6093 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6094 ExtraArgs.AddToScope);
6095
6096 if (Trap.hasErrorOccurred())
6097 Result = 0;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006098 }
Richard Smith2d670972013-08-17 00:46:16 +00006099
6100 if (Result) {
6101 // Determine which correction we picked.
6102 Decl *Canonical = Result->getCanonicalDecl();
6103 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6104 I != E; ++I)
6105 if ((*I)->getCanonicalDecl() == Canonical)
6106 Correction.setCorrectionDecl(*I);
6107
6108 SemaRef.diagnoseTypo(
6109 Correction,
6110 SemaRef.PDiag(IsLocalFriend
6111 ? diag::err_no_matching_local_friend_suggest
6112 : diag::err_member_decl_does_not_match_suggest)
6113 << Name << NewDC << IsDefinition);
6114 return Result;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006115 }
Richard Smith2d670972013-08-17 00:46:16 +00006116
6117 // Pretend the typo correction never occurred
6118 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6119 ExtraArgs.D.getIdentifierLoc());
6120 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6121 Previous.clear();
6122 Previous.setLookupName(Name);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006123 }
6124
Richard Smith2d670972013-08-17 00:46:16 +00006125 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6126 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006127
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006128 bool NewFDisConst = false;
6129 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikie4ef832f2012-08-10 00:55:35 +00006130 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006131
Craig Topper8bc99dd2013-07-04 03:15:42 +00006132 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006133 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6134 NearMatch != NearMatchEnd; ++NearMatch) {
6135 FunctionDecl *FD = NearMatch->first;
Richard Smith4e9686b2013-08-09 04:35:01 +00006136 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6137 bool FDisConst = MD && MD->isConst();
6138 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006139
Richard Smitha41c97a2013-09-20 01:15:31 +00006140 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006141 if (unsigned Idx = NearMatch->second) {
6142 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smith1c931be2012-04-02 18:40:40 +00006143 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6144 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith4e9686b2013-08-09 04:35:01 +00006145 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6146 : diag::note_local_decl_close_param_match)
6147 << Idx << FDParam->getType()
6148 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006149 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006150 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006151 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006152 } else
Richard Smith4e9686b2013-08-09 04:35:01 +00006153 SemaRef.Diag(FD->getLocation(),
6154 IsMember ? diag::note_member_def_close_match
6155 : diag::note_local_decl_close_match);
John McCall29ae6e52010-10-13 05:45:15 +00006156 }
Richard Smith2d670972013-08-17 00:46:16 +00006157 return 0;
John McCall29ae6e52010-10-13 05:45:15 +00006158}
6159
David Blaikied662a792011-10-19 22:56:21 +00006160static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6161 Declarator &D) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006162 switch (D.getDeclSpec().getStorageClassSpec()) {
6163 default: llvm_unreachable("Unknown storage class!");
6164 case DeclSpec::SCS_auto:
6165 case DeclSpec::SCS_register:
6166 case DeclSpec::SCS_mutable:
6167 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6168 diag::err_typecheck_sclass_func);
6169 D.setInvalidType();
6170 break;
6171 case DeclSpec::SCS_unspecified: break;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00006172 case DeclSpec::SCS_extern:
6173 if (D.getDeclSpec().isExternInLinkageSpec())
6174 return SC_None;
6175 return SC_Extern;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006176 case DeclSpec::SCS_static: {
6177 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6178 // C99 6.7.1p5:
6179 // The declaration of an identifier for a function that has
6180 // block scope shall have no explicit storage-class specifier
6181 // other than extern
6182 // See also (C++ [dcl.stc]p4).
6183 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6184 diag::err_static_block_func);
6185 break;
6186 } else
6187 return SC_Static;
6188 }
6189 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6190 }
6191
6192 // No explicit storage class has already been returned
6193 return SC_None;
6194}
6195
6196static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6197 DeclContext *DC, QualType &R,
6198 TypeSourceInfo *TInfo,
6199 FunctionDecl::StorageClass SC,
6200 bool &IsVirtualOkay) {
6201 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6202 DeclarationName Name = NameInfo.getName();
6203
6204 FunctionDecl *NewFD = 0;
6205 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006206
David Blaikie4e4d0842012-03-11 07:00:24 +00006207 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006208 // Determine whether the function was written with a
6209 // prototype. This true when:
6210 // - there is a prototype in the declarator, or
6211 // - the type R of the function is some kind of typedef or other reference
6212 // to a type name (which eventually refers to a function type).
6213 bool HasPrototype =
6214 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6215 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6216
David Blaikied662a792011-10-19 22:56:21 +00006217 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006218 D.getLocStart(), NameInfo, R,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006219 TInfo, SC, isInline,
6220 HasPrototype, false);
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006221 if (D.isInvalidType())
6222 NewFD->setInvalidDecl();
6223
6224 // Set the lexical context.
6225 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6226
6227 return NewFD;
6228 }
6229
6230 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6231 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6232
6233 // Check that the return type is not an abstract class type.
6234 // For record types, this is done by the AbstractClassUsageDiagnoser once
6235 // the class has been completely parsed.
6236 if (!DC->isRecord() &&
6237 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6238 R->getAs<FunctionType>()->getResultType(),
6239 diag::err_abstract_type_in_decl,
6240 SemaRef.AbstractReturnType))
6241 D.setInvalidType();
6242
6243 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6244 // This is a C++ constructor declaration.
6245 assert(DC->isRecord() &&
6246 "Constructors can only be declared in a member context");
6247
6248 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6249 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006250 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006251 R, TInfo, isExplicit, isInline,
6252 /*isImplicitlyDeclared=*/false,
6253 isConstexpr);
6254
6255 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6256 // This is a C++ destructor declaration.
6257 if (DC->isRecord()) {
6258 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6259 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6260 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6261 SemaRef.Context, Record,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006262 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006263 NameInfo, R, TInfo, isInline,
6264 /*isImplicitlyDeclared=*/false);
6265
6266 // If the class is complete, then we now create the implicit exception
6267 // specification. If the class is incomplete or dependent, we can't do
6268 // it yet.
Richard Smith80ad52f2013-01-02 11:42:31 +00006269 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006270 Record->getDefinition() && !Record->isBeingDefined() &&
6271 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6272 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6273 }
6274
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006275 // The Microsoft ABI requires that we perform the destructor body
6276 // checks (i.e. operator delete() lookup) at every declaration, as
6277 // any translation unit may need to emit a deleting destructor.
6278 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6279 !Record->isDependentType() && Record->getDefinition() &&
6280 !Record->isBeingDefined()) {
6281 SemaRef.CheckDestructor(NewDD);
6282 }
6283
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006284 IsVirtualOkay = true;
6285 return NewDD;
6286
6287 } else {
6288 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6289 D.setInvalidType();
6290
6291 // Create a FunctionDecl to satisfy the function definition parsing
6292 // code path.
6293 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006294 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006295 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006296 SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006297 /*hasPrototype=*/true, isConstexpr);
6298 }
6299
6300 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6301 if (!DC->isRecord()) {
6302 SemaRef.Diag(D.getIdentifierLoc(),
6303 diag::err_conv_function_not_member);
6304 return 0;
6305 }
6306
6307 SemaRef.CheckConversionDeclarator(D, R, SC);
6308 IsVirtualOkay = true;
6309 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006310 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006311 R, TInfo, isInline, isExplicit,
6312 isConstexpr, SourceLocation());
6313
6314 } else if (DC->isRecord()) {
6315 // If the name of the function is the same as the name of the record,
6316 // then this must be an invalid constructor that has a return type.
6317 // (The parser checks for a return type and makes the declarator a
6318 // constructor if it has no return type).
6319 if (Name.getAsIdentifierInfo() &&
6320 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6321 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6322 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6323 << SourceRange(D.getIdentifierLoc());
6324 return 0;
6325 }
6326
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006327 // This is a C++ method declaration.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006328 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6329 cast<CXXRecordDecl>(DC),
6330 D.getLocStart(), NameInfo, R,
6331 TInfo, SC, isInline,
6332 isConstexpr, SourceLocation());
6333 IsVirtualOkay = !Ret->isStatic();
6334 return Ret;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006335 } else {
6336 // Determine whether the function was written with a
6337 // prototype. This true when:
6338 // - we're in C++ (where every function has a prototype),
6339 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006340 D.getLocStart(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006341 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006342 true/*HasPrototype*/, isConstexpr);
6343 }
6344}
6345
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006346void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6347 // In C++, the empty parameter-type-list must be spelled "void"; a
6348 // typedef of void is not permitted.
6349 if (getLangOpts().CPlusPlus &&
6350 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6351 bool IsTypeAlias = false;
6352 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6353 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6354 else if (const TemplateSpecializationType *TST =
6355 Param->getType()->getAs<TemplateSpecializationType>())
6356 IsTypeAlias = TST->isTypeAlias();
6357 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6358 << IsTypeAlias;
6359 }
6360}
6361
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00006362enum OpenCLParamType {
6363 ValidKernelParam,
6364 PtrPtrKernelParam,
6365 PtrKernelParam,
6366 InvalidKernelParam,
6367 RecordKernelParam
6368};
6369
6370static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6371 if (PT->isPointerType()) {
6372 QualType PointeeType = PT->getPointeeType();
6373 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6374 }
6375
6376 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6377 // be used as builtin types.
6378
6379 if (PT->isImageType())
6380 return PtrKernelParam;
6381
6382 if (PT->isBooleanType())
6383 return InvalidKernelParam;
6384
6385 if (PT->isEventT())
6386 return InvalidKernelParam;
6387
6388 if (PT->isHalfType())
6389 return InvalidKernelParam;
6390
6391 if (PT->isRecordType())
6392 return RecordKernelParam;
6393
6394 return ValidKernelParam;
6395}
6396
6397static void checkIsValidOpenCLKernelParameter(
6398 Sema &S,
6399 Declarator &D,
6400 ParmVarDecl *Param,
6401 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6402 QualType PT = Param->getType();
6403
6404 // Cache the valid types we encounter to avoid rechecking structs that are
6405 // used again
6406 if (ValidTypes.count(PT.getTypePtr()))
6407 return;
6408
6409 switch (getOpenCLKernelParameterType(PT)) {
6410 case PtrPtrKernelParam:
6411 // OpenCL v1.2 s6.9.a:
6412 // A kernel function argument cannot be declared as a
6413 // pointer to a pointer type.
6414 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6415 D.setInvalidType();
6416 return;
6417
6418 // OpenCL v1.2 s6.9.k:
6419 // Arguments to kernel functions in a program cannot be declared with the
6420 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6421 // uintptr_t or a struct and/or union that contain fields declared to be
6422 // one of these built-in scalar types.
6423
6424 case InvalidKernelParam:
6425 // OpenCL v1.2 s6.8 n:
6426 // A kernel function argument cannot be declared
6427 // of event_t type.
6428 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6429 D.setInvalidType();
6430 return;
6431
6432 case PtrKernelParam:
6433 case ValidKernelParam:
6434 ValidTypes.insert(PT.getTypePtr());
6435 return;
6436
6437 case RecordKernelParam:
6438 break;
6439 }
6440
6441 // Track nested structs we will inspect
6442 SmallVector<const Decl *, 4> VisitStack;
6443
6444 // Track where we are in the nested structs. Items will migrate from
6445 // VisitStack to HistoryStack as we do the DFS for bad field.
6446 SmallVector<const FieldDecl *, 4> HistoryStack;
6447 HistoryStack.push_back((const FieldDecl *) 0);
6448
6449 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6450 VisitStack.push_back(PD);
6451
6452 assert(VisitStack.back() && "First decl null?");
6453
6454 do {
6455 const Decl *Next = VisitStack.pop_back_val();
6456 if (!Next) {
6457 assert(!HistoryStack.empty());
6458 // Found a marker, we have gone up a level
6459 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6460 ValidTypes.insert(Hist->getType().getTypePtr());
6461
6462 continue;
6463 }
6464
6465 // Adds everything except the original parameter declaration (which is not a
6466 // field itself) to the history stack.
6467 const RecordDecl *RD;
6468 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6469 HistoryStack.push_back(Field);
6470 RD = Field->getType()->castAs<RecordType>()->getDecl();
6471 } else {
6472 RD = cast<RecordDecl>(Next);
6473 }
6474
6475 // Add a null marker so we know when we've gone back up a level
6476 VisitStack.push_back((const Decl *) 0);
6477
6478 for (RecordDecl::field_iterator I = RD->field_begin(),
6479 E = RD->field_end(); I != E; ++I) {
6480 const FieldDecl *FD = *I;
6481 QualType QT = FD->getType();
6482
6483 if (ValidTypes.count(QT.getTypePtr()))
6484 continue;
6485
6486 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6487 if (ParamType == ValidKernelParam)
6488 continue;
6489
6490 if (ParamType == RecordKernelParam) {
6491 VisitStack.push_back(FD);
6492 continue;
6493 }
6494
6495 // OpenCL v1.2 s6.9.p:
6496 // Arguments to kernel functions that are declared to be a struct or union
6497 // do not allow OpenCL objects to be passed as elements of the struct or
6498 // union.
6499 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6500 S.Diag(Param->getLocation(),
6501 diag::err_record_with_pointers_kernel_param)
6502 << PT->isUnionType()
6503 << PT;
6504 } else {
6505 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6506 }
6507
6508 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6509 << PD->getDeclName();
6510
6511 // We have an error, now let's go back up through history and show where
6512 // the offending field came from
6513 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6514 E = HistoryStack.end(); I != E; ++I) {
6515 const FieldDecl *OuterField = *I;
6516 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6517 << OuterField->getType();
6518 }
6519
6520 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6521 << QT->isPointerType()
6522 << QT;
6523 D.setInvalidType();
6524 return;
6525 }
6526 } while (!VisitStack.empty());
6527}
6528
Mike Stump1eb44332009-09-09 15:08:12 +00006529NamedDecl*
Nick Lewycky25af0912011-07-02 02:05:12 +00006530Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006531 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00006532 MultiTemplateParamsArg TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006533 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006534 QualType R = TInfo->getType();
6535
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006536 assert(R.getTypePtr()->isFunctionType());
6537
Abramo Bagnara25777432010-08-11 22:01:17 +00006538 // TODO: consider using NameInfo for diagnostic.
6539 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6540 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006541 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006542
Richard Smithec642442013-04-12 22:46:28 +00006543 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6544 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6545 diag::err_invalid_thread)
6546 << DeclSpec::getSpecifierName(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00006547
Reid Klecknerd1a32c32013-10-08 00:58:57 +00006548 if (D.isFirstDeclarationOfMember())
6549 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckneref072032013-08-27 23:08:25 +00006550
Douglas Gregor3922ed02010-12-10 19:28:19 +00006551 bool isFriend = false;
Douglas Gregor3922ed02010-12-10 19:28:19 +00006552 FunctionTemplateDecl *FunctionTemplate = 0;
6553 bool isExplicitSpecialization = false;
6554 bool isFunctionTemplateSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006555
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006556 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006557 bool HasExplicitTemplateArgs = false;
6558 TemplateArgumentListInfo TemplateArgs;
6559
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006560 bool isVirtualOkay = false;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006561
Richard Smitha41c97a2013-09-20 01:15:31 +00006562 DeclContext *OriginalDC = DC;
6563 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6564
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006565 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6566 isVirtualOkay);
6567 if (!NewFD) return 0;
6568
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00006569 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6570 NewFD->setTopLevelDeclInObjCContainer();
6571
Richard Smitha41c97a2013-09-20 01:15:31 +00006572 // Set the lexical context. If this is a function-scope declaration, or has a
6573 // C++ scope specifier, or is the object of a friend declaration, the lexical
6574 // context will be different from the semantic context.
6575 NewFD->setLexicalDeclContext(CurContext);
6576
6577 if (IsLocalExternDecl)
6578 NewFD->setLocalExternDecl();
6579
David Blaikie4e4d0842012-03-11 07:00:24 +00006580 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006581 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00006582 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6583 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006584 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006585 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006586 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnarab0a2fcc2011-03-18 15:21:59 +00006587 // C++ [class.friend]p5
6588 // A function can be defined in a friend declaration of a
6589 // class . . . . Such a function is implicitly inline.
6590 NewFD->setImplicitlyInline();
6591 }
6592
John McCalle402e722012-09-25 07:32:39 +00006593 // If this is a method defined in an __interface, and is not a constructor
6594 // or an overloaded operator, then set the pure flag (isVirtual will already
6595 // return true).
6596 if (const CXXRecordDecl *Parent =
6597 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6598 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matos6666ed42012-08-31 18:45:21 +00006599 NewFD->setPure(true);
6600 }
6601
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006602 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006603 isExplicitSpecialization = false;
6604 isFunctionTemplateSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006605 if (D.isInvalidType())
6606 NewFD->setInvalidDecl();
Richard Smitha41c97a2013-09-20 01:15:31 +00006607
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006608 // Match up the template parameter lists with the scope specifier, then
6609 // determine whether we have a template or a template specialization.
6610 bool Invalid = false;
Robert Wilhelm1169e2f2013-07-21 15:20:44 +00006611 if (TemplateParameterList *TemplateParams =
6612 MatchTemplateParametersToScopeSpecifier(
6613 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6614 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6615 isExplicitSpecialization, Invalid)) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006616 if (TemplateParams->size() > 0) {
6617 // This is a function template
Abramo Bagnara9b934882010-06-12 08:15:14 +00006618
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006619 // Check that we can declare a template here.
6620 if (CheckTemplateDeclScope(S, TemplateParams))
6621 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006622
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006623 // A destructor cannot be a template.
6624 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6625 Diag(NewFD->getLocation(), diag::err_destructor_template);
6626 return 0;
John McCall5fd378b2010-03-24 08:27:58 +00006627 }
Douglas Gregor20606502011-10-14 15:31:12 +00006628
6629 // If we're adding a template to a dependent context, we may need to
David Blaikied662a792011-10-19 22:56:21 +00006630 // rebuilding some of the types used within the template parameter list,
Douglas Gregor20606502011-10-14 15:31:12 +00006631 // now that we know what the current instantiation is.
6632 if (DC->isDependentContext()) {
6633 ContextRAII SavedContext(*this, DC);
6634 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6635 Invalid = true;
6636 }
6637
John McCall5fd378b2010-03-24 08:27:58 +00006638
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006639 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6640 NewFD->getLocation(),
6641 Name, TemplateParams,
6642 NewFD);
6643 FunctionTemplate->setLexicalDeclContext(CurContext);
6644 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6645
6646 // For source fidelity, store the other template param lists.
6647 if (TemplateParamLists.size() > 1) {
6648 NewFD->setTemplateParameterListsInfo(Context,
6649 TemplateParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00006650 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006651 }
6652 } else {
6653 // This is a function template specialization.
6654 isFunctionTemplateSpecialization = true;
6655 // For source fidelity, store all the template param lists.
6656 NewFD->setTemplateParameterListsInfo(Context,
6657 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006658 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006659
6660 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6661 if (isFriend) {
6662 // We want to remove the "template<>", found here.
6663 SourceRange RemoveRange = TemplateParams->getSourceRange();
6664
6665 // If we remove the template<> and the name is not a
6666 // template-id, we're actually silently creating a problem:
6667 // the friend declaration will refer to an untemplated decl,
6668 // and clearly the user wants a template specialization. So
6669 // we need to insert '<>' after the name.
6670 SourceLocation InsertLoc;
6671 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6672 InsertLoc = D.getName().getSourceRange().getEnd();
6673 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6674 }
6675
6676 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6677 << Name << RemoveRange
6678 << FixItHint::CreateRemoval(RemoveRange)
6679 << FixItHint::CreateInsertion(InsertLoc, "<>");
6680 }
6681 }
6682 }
6683 else {
6684 // All template param lists were matched against the scope specifier:
6685 // this is NOT (an explicit specialization of) a template.
6686 if (TemplateParamLists.size() > 0)
6687 // For source fidelity, store all the template param lists.
6688 NewFD->setTemplateParameterListsInfo(Context,
6689 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006690 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006691 }
6692
6693 if (Invalid) {
6694 NewFD->setInvalidDecl();
6695 if (FunctionTemplate)
6696 FunctionTemplate->setInvalidDecl();
6697 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006698
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006699 // C++ [dcl.fct.spec]p5:
6700 // The virtual specifier shall only be used in declarations of
6701 // nonstatic class member functions that appear within a
6702 // member-specification of a class declaration; see 10.3.
6703 //
6704 if (isVirtual && !NewFD->isInvalidDecl()) {
6705 if (!isVirtualOkay) {
6706 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6707 diag::err_virtual_non_function);
6708 } else if (!CurContext->isRecord()) {
6709 // 'virtual' was specified outside of the class.
Anders Carlssonf1602a52011-01-22 14:43:56 +00006710 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6711 diag::err_virtual_out_of_class)
6712 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6713 } else if (NewFD->getDescribedFunctionTemplate()) {
6714 // C++ [temp.mem]p3:
6715 // A member function template shall not be virtual.
6716 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6717 diag::err_virtual_member_function_template)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006718 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6719 } else {
6720 // Okay: Add virtual to the method.
6721 NewFD->setVirtualAsWritten(true);
John McCall7ad650f2010-03-24 07:46:06 +00006722 }
Richard Smith60e141e2013-05-04 07:00:32 +00006723
6724 if (getLangOpts().CPlusPlus1y &&
6725 NewFD->getResultType()->isUndeducedType())
6726 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00006727 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006728
Richard Smith37e849a2013-08-14 20:16:31 +00006729 if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() &&
6730 NewFD->getResultType()->isUndeducedType()) {
6731 // If the function template is referenced directly (for instance, as a
6732 // member of the current instantiation), pretend it has a dependent type.
6733 // This is not really justified by the standard, but is the only sane
6734 // thing to do.
6735 const FunctionProtoType *FPT =
6736 NewFD->getType()->castAs<FunctionProtoType>();
6737 QualType Result = SubstAutoType(FPT->getResultType(),
6738 Context.DependentTy);
6739 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6740 FPT->getExtProtoInfo()));
6741 }
6742
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006743 // C++ [dcl.fct.spec]p3:
David Blaikied662a792011-10-19 22:56:21 +00006744 // The inline specifier shall not appear on a block scope function
6745 // declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006746 if (isInline && !NewFD->isInvalidDecl()) {
6747 if (CurContext->isFunctionOrMethod()) {
6748 // 'inline' is not allowed on block scope function declaration.
6749 Diag(D.getDeclSpec().getInlineSpecLoc(),
6750 diag::err_inline_declaration_block_scope) << Name
6751 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6752 }
6753 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006754
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006755 // C++ [dcl.fct.spec]p6:
6756 // The explicit specifier shall be used only in the declaration of a
David Blaikied662a792011-10-19 22:56:21 +00006757 // constructor or conversion function within its class definition;
6758 // see 12.3.1 and 12.3.2.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006759 if (isExplicit && !NewFD->isInvalidDecl()) {
6760 if (!CurContext->isRecord()) {
6761 // 'explicit' was specified outside of the class.
6762 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6763 diag::err_explicit_out_of_class)
6764 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6765 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6766 !isa<CXXConversionDecl>(NewFD)) {
6767 // 'explicit' was specified on a function that wasn't a constructor
6768 // or conversion function.
6769 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6770 diag::err_explicit_non_ctor_or_conv_function)
6771 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6772 }
6773 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006774
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006775 if (isConstexpr) {
Richard Smith21c8fa82013-01-14 05:37:29 +00006776 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006777 // are implicitly inline.
6778 NewFD->setImplicitlyInline();
6779
Richard Smith21c8fa82013-01-14 05:37:29 +00006780 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006781 // be either constructors or to return a literal type. Therefore,
6782 // destructors cannot be declared constexpr.
6783 if (isa<CXXDestructorDecl>(NewFD))
Richard Smith9f569cc2011-10-01 02:31:28 +00006784 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006785 }
6786
Douglas Gregor8d267c52011-09-09 02:06:17 +00006787 // If __module_private__ was specified, mark the function accordingly.
6788 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00006789 if (isFunctionTemplateSpecialization) {
6790 SourceLocation ModulePrivateLoc
6791 = D.getDeclSpec().getModulePrivateSpecLoc();
6792 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6793 << 0
6794 << FixItHint::CreateRemoval(ModulePrivateLoc);
6795 } else {
6796 NewFD->setModulePrivate();
6797 if (FunctionTemplate)
6798 FunctionTemplate->setModulePrivate();
6799 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00006800 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006801
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006802 if (isFriend) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006803 if (FunctionTemplate) {
Richard Smith22050f22013-07-17 23:53:16 +00006804 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006805 FunctionTemplate->setAccess(AS_public);
6806 }
Richard Smith22050f22013-07-17 23:53:16 +00006807 NewFD->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006808 NewFD->setAccess(AS_public);
6809 }
6810
Douglas Gregor45fa5602011-11-07 20:56:01 +00006811 // If a function is defined as defaulted or deleted, mark it as such now.
6812 switch (D.getFunctionDefinitionKind()) {
6813 case FDK_Declaration:
6814 case FDK_Definition:
6815 break;
6816
6817 case FDK_Defaulted:
6818 NewFD->setDefaulted();
6819 break;
6820
6821 case FDK_Deleted:
6822 NewFD->setDeletedAsWritten();
6823 break;
6824 }
6825
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006826 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6827 D.isFunctionDefinition()) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00006828 // C++ [class.mfct]p2:
6829 // A member function may be defined (8.4) in its class definition, in
6830 // which case it is an inline member function (7.1.2)
John McCallbfdcdc82010-12-15 04:00:32 +00006831 NewFD->setImplicitlyInline();
6832 }
6833
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006834 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6835 !CurContext->isRecord()) {
6836 // C++ [class.static]p1:
6837 // A data or function member of a class may be declared static
6838 // in a class definition, in which case it is a static member of
6839 // the class.
6840
6841 // Complain about the 'static' specifier if it's on an out-of-line
6842 // member function definition.
6843 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6844 diag::err_static_out_of_line)
6845 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6846 }
Richard Smith444d3842012-10-20 08:26:51 +00006847
6848 // C++11 [except.spec]p15:
6849 // A deallocation function with no exception-specification is treated
6850 // as if it were specified with noexcept(true).
6851 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6852 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6853 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006854 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith444d3842012-10-20 08:26:51 +00006855 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6856 EPI.ExceptionSpecType = EST_BasicNoexcept;
6857 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00006858 FPT->getArgTypes(), EPI));
Richard Smith444d3842012-10-20 08:26:51 +00006859 }
David Majnemerd2b0cf32013-10-20 05:40:29 +00006860
6861 // C++11 [replacement.functions]p3:
6862 // The program's definitions shall not be specified as inline.
David Majnemer3abf5f62013-10-21 00:25:32 +00006863 //
6864 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
David Majnemerd2b0cf32013-10-20 05:40:29 +00006865 if (isInline && NewFD->isReplaceableGlobalAllocationFunction())
6866 Diag(D.getDeclSpec().getInlineSpecLoc(),
6867 diag::err_operator_new_delete_declared_inline)
6868 << NewFD->getDeclName();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00006869 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006870
6871 // Filter out previous declarations that don't match the scope.
Richard Smitha41c97a2013-09-20 01:15:31 +00006872 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006873 isExplicitSpecialization ||
6874 isFunctionTemplateSpecialization);
Richard Smithdd9459f2013-08-13 18:18:50 +00006875
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006876 // Handle GNU asm-label extension (encoded as an attribute).
6877 if (Expr *E = (Expr*) D.getAsmLabel()) {
6878 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00006879 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00006880 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6881 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00006882 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6883 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6884 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6885 if (I != ExtnameUndeclaredIdentifiers.end()) {
6886 NewFD->addAttr(I->second);
6887 ExtnameUndeclaredIdentifiers.erase(I);
6888 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006889 }
6890
Chris Lattner2dbd2852009-04-25 06:12:16 +00006891 // Copy the parameter declarations from the declarator D to the function
6892 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006893 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00006894 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006895 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006896
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006897 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6898 // function that takes no arguments, not a function that takes a
6899 // single void argument.
6900 // We let through "const void" here because Sema::GetTypeForDeclarator
6901 // already checks for that case.
6902 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6903 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006904 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00006905 // Empty arg list, don't push any params.
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006906 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006907 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006908 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00006909 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006910 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6911 Param->setDeclContext(NewFD);
6912 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00006913
6914 if (Param->isInvalidDecl())
6915 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006916 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006917 }
Mike Stump1eb44332009-09-09 15:08:12 +00006918
John McCall183700f2009-09-21 23:43:11 +00006919 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00006920 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006921 // following example, we'll need to synthesize (unnamed)
6922 // parameters for use in the declaration.
6923 //
6924 // @code
6925 // typedef void fn(int);
6926 // fn f;
6927 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00006928
Chris Lattner1ad9b282009-04-25 06:03:53 +00006929 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00006930 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6931 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00006932 ParmVarDecl *Param =
6933 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00006934 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00006935 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006936 }
Chris Lattner84bb9442009-04-25 18:38:18 +00006937 } else {
6938 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6939 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006940 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00006941
Chris Lattner2dbd2852009-04-25 06:12:16 +00006942 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00006943 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00006944
James Molloy16f1f712012-02-29 10:24:19 +00006945 // Find all anonymous symbols defined during the declaration of this function
6946 // and add to NewFD. This lets us track decls such 'enum Y' in:
6947 //
6948 // void f(enum Y {AA} x) {}
6949 //
6950 // which would otherwise incorrectly end up in the translation unit scope.
6951 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6952 DeclsInPrototypeScope.clear();
6953
Richard Smith7586a6e2013-01-30 05:45:05 +00006954 if (D.getDeclSpec().isNoreturnSpecified())
6955 NewFD->addAttr(
6956 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6957 Context));
6958
Richard Smithb03a9df2012-03-13 05:56:40 +00006959 // Functions returning a variably modified type violate C99 6.7.5.2p2
6960 // because all functions have linkage.
6961 if (!NewFD->isInvalidDecl() &&
6962 NewFD->getResultType()->isVariablyModifiedType()) {
6963 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6964 NewFD->setInvalidDecl();
6965 }
6966
Rafael Espindola98ae8342012-05-10 02:50:16 +00006967 // Handle attributes.
Richard Smith4a97b8e2013-08-29 00:47:48 +00006968 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindola98ae8342012-05-10 02:50:16 +00006969
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006970 QualType RetType = NewFD->getResultType();
6971 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6972 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6973 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6974 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006975 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramera32966f2013-10-16 16:21:04 +00006976 // Attach the attribute to the new decl. Don't apply the attribute if it
6977 // returns an instance of the class (e.g. assignment operators).
6978 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006979 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6980 Context));
6981 }
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006982 }
6983
David Blaikie4e4d0842012-03-11 07:00:24 +00006984 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006985 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00006986 bool isExplicitSpecialization=false;
David Majnemerc371db62013-07-06 02:13:46 +00006987 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6988 CheckMain(NewFD, D.getDeclSpec());
6989
David Majnemere9f6f332013-09-16 22:44:20 +00006990 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6991 CheckMSVCRTEntryPoint(NewFD);
6992
David Majnemerc371db62013-07-06 02:13:46 +00006993 if (!NewFD->isInvalidDecl())
Richard Smithb03a9df2012-03-13 05:56:40 +00006994 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6995 isExplicitSpecialization));
Fariborz Jahanian37c765a2012-09-05 17:52:12 +00006996 else if (!Previous.empty())
Richard Smithdd9459f2013-08-13 18:18:50 +00006997 // Make graceful recovery from an invalid redeclaration.
6998 D.setRedeclaration(true);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006999 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007000 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7001 "previous declaration set still overloaded");
7002 } else {
7003 // If the declarator is a template-id, translate the parser's template
7004 // argument list into our AST format.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007005 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7006 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7007 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7008 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00007009 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007010 TemplateId->NumArgs);
7011 translateTemplateArguments(TemplateArgsPtr,
7012 TemplateArgs);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007013
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007014 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007015
Douglas Gregor89b9f102011-06-06 15:22:55 +00007016 if (NewFD->isInvalidDecl()) {
7017 HasExplicitTemplateArgs = false;
7018 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00007019 // Function template with explicit template arguments.
7020 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7021 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7022
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007023 HasExplicitTemplateArgs = false;
7024 } else if (!isFunctionTemplateSpecialization &&
7025 !D.getDeclSpec().isFriendSpecified()) {
7026 // We have encountered something that the user meant to be a
7027 // specialization (because it has explicitly-specified template
7028 // arguments) but that was not introduced with a "template<>" (or had
7029 // too few of them).
Larisse Voufoef4579c2013-08-06 01:03:05 +00007030 // FIXME: Differentiate between attempts for explicit instantiations
7031 // (starting with "template") and the rest.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007032 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7033 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7034 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00007035 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00007036 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007037 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00007038 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007039 // "friend void foo<>(int);" is an implicit specialization decl.
7040 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00007041 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007042 } else if (isFriend && isFunctionTemplateSpecialization) {
7043 // This combination is only possible in a recovery case; the user
7044 // wrote something like:
7045 // template <> friend void foo(int);
7046 // which we're recovering from as if the user had written:
7047 // friend void foo<>(int);
7048 // Go ahead and fake up a template id.
7049 HasExplicitTemplateArgs = true;
7050 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7051 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007052 }
John McCall29ae6e52010-10-13 05:45:15 +00007053
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007054 // If it's a friend (and only if it's a friend), it's possible
7055 // that either the specialized function type or the specialized
7056 // template is dependent, and therefore matching will fail. In
7057 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007058 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007059 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007060 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7061 TemplateSpecializationType::anyDependentTemplateArguments(
7062 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7063 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007064 assert(HasExplicitTemplateArgs &&
7065 "friend function specialization without template args");
7066 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7067 Previous))
7068 NewFD->setInvalidDecl();
7069 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007070 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00007071 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007072 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00007073 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007074 diag::ext_function_specialization_in_class :
7075 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007076 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007077 } else if (CheckFunctionTemplateSpecialization(NewFD,
7078 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7079 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007080 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00007081
7082 // C++ [dcl.stc]p1:
7083 // A storage-class-specifier shall not be specified in an explicit
7084 // specialization (14.7.3)
Richard Trieu62ab0102013-05-16 02:14:08 +00007085 FunctionTemplateSpecializationInfo *Info =
7086 NewFD->getTemplateSpecializationInfo();
7087 if (Info && SC != SC_None) {
7088 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor0f9dc862011-06-17 05:09:08 +00007089 Diag(NewFD->getLocation(),
7090 diag::err_explicit_specialization_inconsistent_storage_class)
7091 << SC
7092 << FixItHint::CreateRemoval(
7093 D.getDeclSpec().getStorageClassSpecLoc());
7094
7095 else
7096 Diag(NewFD->getLocation(),
7097 diag::ext_explicit_specialization_storage_class)
7098 << FixItHint::CreateRemoval(
7099 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00007100 }
7101
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007102 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7103 if (CheckMemberSpecialization(NewFD, Previous))
7104 NewFD->setInvalidDecl();
7105 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007106
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007107 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00007108 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemerc371db62013-07-06 02:13:46 +00007109 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7110 CheckMain(NewFD, D.getDeclSpec());
7111
David Majnemere9f6f332013-09-16 22:44:20 +00007112 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7113 CheckMSVCRTEntryPoint(NewFD);
7114
David Blaikie14068e82011-09-08 06:33:04 +00007115 if (NewFD->isInvalidDecl()) {
7116 // If this is a class member, mark the class invalid immediately.
7117 // This avoids some consistency errors later.
7118 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7119 methodDecl->getParent()->setInvalidDecl();
David Majnemerc371db62013-07-06 02:13:46 +00007120 } else
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007121 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7122 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00007123 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007124
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007125 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007126 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7127 "previous declaration set still overloaded");
7128
7129 NamedDecl *PrincipalDecl = (FunctionTemplate
7130 ? cast<NamedDecl>(FunctionTemplate)
7131 : NewFD);
7132
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007133 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007134 AccessSpecifier Access = AS_public;
7135 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00007136 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007137
7138 NewFD->setAccess(Access);
7139 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007140 }
7141
7142 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7143 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7144 PrincipalDecl->setNonMemberOperator();
7145
7146 // If we have a function template, check the template parameter
7147 // list. This will check and merge default template arguments.
7148 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00007149 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00007150 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007151 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00007152 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00007153 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007154 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00007155 ? TPC_FriendFunctionTemplateDefinition
7156 : TPC_FriendFunctionTemplate)
7157 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00007158 DC && DC->isRecord() &&
7159 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00007160 ? TPC_ClassTemplateMember
7161 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007162 }
7163
7164 if (NewFD->isInvalidDecl()) {
7165 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007166 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00007167 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007168 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007169 // Fake up an access specifier if it's supposed to be a class member.
7170 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7171 NewFD->setAccess(AS_public);
7172
7173 // Qualified decls generally require a previous declaration.
7174 if (D.getCXXScopeSpec().isSet()) {
7175 // ...with the major exception of templated-scope or
7176 // dependent-scope friend declarations.
7177
7178 // TODO: we currently also suppress this check in dependent
7179 // contexts because (1) the parameter depth will be off when
7180 // matching friend templates and (2) we might actually be
7181 // selecting a friend based on a dependent factor. But there
7182 // are situations where these conditions don't apply and we
7183 // can actually do this check immediately.
7184 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007185 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007186 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7187 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007188 // ignore these
7189 } else {
7190 // The user tried to provide an out-of-line definition for a
7191 // function that is a member of a class or namespace, but there
7192 // was no such member function declared (C++ [class.mfct]p2,
7193 // C++ [namespace.memdef]p2). For example:
7194 //
7195 // class X {
7196 // void f() const;
7197 // };
7198 //
7199 // void X::f() { } // ill-formed
7200 //
7201 // Complain about this problem, and attempt to suggest close
7202 // matches (e.g., those that differ only in cv-qualifiers and
7203 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007204
Richard Smith4e9686b2013-08-09 04:35:01 +00007205 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7206 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007207 AddToScope = ExtraArgs.AddToScope;
7208 return Result;
7209 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007210 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007211
7212 // Unqualified local friend declarations are required to resolve
7213 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007214 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith4e9686b2013-08-09 04:35:01 +00007215 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7216 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007217 AddToScope = ExtraArgs.AddToScope;
7218 return Result;
7219 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007220 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007221
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007222 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007223 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00007224 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007225 // An out-of-line member function declaration must also be a
7226 // definition (C++ [dcl.meaning]p1).
7227 // Note that this is not the case for explicit specializations of
7228 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00007229 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7230 // extension for compatibility with old SWIG code which likes to
7231 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007232 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7233 << D.getCXXScopeSpec().getRange();
7234 }
7235 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00007236
Rafael Espindola65611bf2013-03-02 21:41:48 +00007237 ProcessPragmaWeak(S, NewFD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00007238 checkAttributesAfterMerging(*this, *NewFD);
7239
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007240 AddKnownFunctionAttributes(NewFD);
7241
Douglas Gregord9455382010-08-06 13:50:58 +00007242 if (NewFD->hasAttr<OverloadableAttr>() &&
7243 !NewFD->getType()->getAs<FunctionProtoType>()) {
7244 Diag(NewFD->getLocation(),
7245 diag::err_attribute_overloadable_no_prototype)
7246 << NewFD;
7247
7248 // Turn this into a variadic function with no parameters.
7249 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckneref072032013-08-27 23:08:25 +00007250 FunctionProtoType::ExtProtoInfo EPI(
7251 Context.getDefaultCallingConvention(true, false));
John McCalle23cf432010-12-14 08:05:40 +00007252 EPI.Variadic = true;
7253 EPI.ExtInfo = FT->getExtInfo();
7254
Dmitri Gribenko55431692013-05-05 00:41:58 +00007255 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00007256 NewFD->setType(R);
7257 }
7258
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007259 // If there's a #pragma GCC visibility in scope, and this isn't a class
7260 // member, set the visibility of this function.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007261 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007262 AddPushedVisibilityAttribute(NewFD);
7263
John McCall8dfac0b2011-09-30 05:12:12 +00007264 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7265 // marking the function.
7266 AddCFAuditedAttribute(NewFD);
7267
Richard Smithaa4bc182013-06-30 09:48:50 +00007268 // If this is the first declaration of an extern C variable, update
7269 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00007270 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00007271 isIncompleteDeclExternC(*this, NewFD))
Richard Smith662f41b2013-06-18 20:15:12 +00007272 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007273
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007274 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007275 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007276
David Blaikie4e4d0842012-03-11 07:00:24 +00007277 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007278 if (FunctionTemplate) {
7279 if (NewFD->isInvalidDecl())
7280 FunctionTemplate->setInvalidDecl();
7281 return FunctionTemplate;
7282 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007283 }
Mike Stump1eb44332009-09-09 15:08:12 +00007284
Guy Benyeie6b9d802013-01-20 12:31:11 +00007285 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyeie6b9d802013-01-20 12:31:11 +00007286 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7287 if ((getLangOpts().OpenCLVersion >= 120)
7288 && (SC == SC_Static)) {
7289 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7290 D.setInvalidType();
7291 }
Tanya Lattner7564bcc2013-01-30 19:48:52 +00007292
7293 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7294 if (!NewFD->getResultType()->isVoidType()) {
7295 Diag(D.getIdentifierLoc(),
7296 diag::err_expected_kernel_void_return_type);
7297 D.setInvalidType();
7298 }
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007299
7300 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007301 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7302 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly98f988d2013-01-29 10:54:06 +00007303 ParmVarDecl *Param = *PI;
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007304 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyeie6b9d802013-01-20 12:31:11 +00007305 }
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00007306 }
7307
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00007308 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007309
David Blaikie4e4d0842012-03-11 07:00:24 +00007310 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007311 if (IdentifierInfo *II = NewFD->getIdentifier())
7312 if (!NewFD->isInvalidDecl() &&
7313 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7314 if (II->isStr("cudaConfigureCall")) {
7315 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7316 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7317
7318 Context.setcudaConfigureCallDecl(NewFD);
7319 }
7320 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007321
7322 // Here we have an function template explicit specialization at class scope.
7323 // The actually specialization will be postponed to template instatiation
7324 // time via the ClassScopeFunctionSpecializationDecl node.
7325 if (isDependentClassScopeExplicitSpecialization) {
7326 ClassScopeFunctionSpecializationDecl *NewSpec =
7327 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber6b020092012-06-25 17:21:05 +00007328 Context, CurContext, SourceLocation(),
7329 cast<CXXMethodDecl>(NewFD),
7330 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007331 CurContext->addDecl(NewSpec);
7332 AddToScope = false;
7333 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007334
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007335 return NewFD;
7336}
7337
7338/// \brief Perform semantic checking of a new function declaration.
7339///
7340/// Performs semantic analysis of the new function declaration
7341/// NewFD. This routine performs all semantic checking that does not
7342/// require the actual declarator involved in the declaration, and is
7343/// used both for the declaration of functions as they are parsed
7344/// (called via ActOnDeclarator) and for the declaration of functions
7345/// that have been instantiated via C++ template instantiation (called
7346/// via InstantiateDecl).
7347///
James Dennettefce31f2012-06-22 08:10:18 +00007348/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorfd056bc2009-10-13 16:30:37 +00007349/// an explicit specialization of the previous declaration.
7350///
Chris Lattnereaaebc72009-04-25 08:06:05 +00007351/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007352///
James Dennettefce31f2012-06-22 08:10:18 +00007353/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007354bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00007355 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007356 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00007357 assert(!NewFD->getResultType()->isVariablyModifiedType()
7358 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00007359
Richard Smithdd9459f2013-08-13 18:18:50 +00007360 // Determine whether the type of this function should be merged with
7361 // a previous visible declaration. This never happens for functions in C++,
7362 // and always happens in C if the previous declaration was visible.
7363 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7364 !Previous.isShadowed();
7365
Douglas Gregor7dc80e12013-01-09 00:47:56 +00007366 // Filter out any non-conflicting previous declarations.
7367 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7368
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007369 bool Redeclaration = false;
Richard Smith21c8fa82013-01-14 05:37:29 +00007370 NamedDecl *OldDecl = 0;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007371
Douglas Gregor04495c82009-02-24 01:23:02 +00007372 // Merge or overload the declaration with an existing declaration of
7373 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00007374 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00007375 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007376 // a declaration that requires merging. If it's an overload,
7377 // there's no more work to do here; we'll just add the new
7378 // function to the scope.
John McCall871b2e72009-12-09 03:35:25 +00007379 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola90cc3902013-04-15 12:49:13 +00007380 NamedDecl *Candidate = Previous.getFoundDecl();
7381 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7382 Redeclaration = true;
7383 OldDecl = Candidate;
7384 }
John McCall871b2e72009-12-09 03:35:25 +00007385 } else {
John McCallad00b772010-06-16 08:42:20 +00007386 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7387 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00007388 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007389 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00007390 break;
7391
7392 case Ovl_NonFunction:
7393 Redeclaration = true;
7394 break;
7395
7396 case Ovl_Overload:
7397 Redeclaration = false;
7398 break;
John McCall68263142009-11-18 22:49:29 +00007399 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00007400
David Blaikie4e4d0842012-03-11 07:00:24 +00007401 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00007402 // If a function name is overloadable in C, then every function
7403 // with that name must be marked "overloadable".
7404 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7405 << Redeclaration << NewFD;
7406 NamedDecl *OverloadedDecl = 0;
7407 if (Redeclaration)
7408 OverloadedDecl = OldDecl;
7409 else if (!Previous.empty())
7410 OverloadedDecl = Previous.getRepresentativeDecl();
7411 if (OverloadedDecl)
7412 Diag(OverloadedDecl->getLocation(),
7413 diag::note_attribute_overloadable_prev_overload);
7414 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7415 Context));
7416 }
John McCall68263142009-11-18 22:49:29 +00007417 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007418 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007419
Richard Smithaa4bc182013-06-30 09:48:50 +00007420 // Check for a previous extern "C" declaration with this name.
7421 if (!Redeclaration &&
7422 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7423 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7424 if (!Previous.empty()) {
7425 // This is an extern "C" declaration with the same name as a previous
7426 // declaration, and thus redeclares that entity...
7427 Redeclaration = true;
7428 OldDecl = Previous.getFoundDecl();
Richard Smithdd9459f2013-08-13 18:18:50 +00007429 MergeTypeWithPrevious = false;
Richard Smithaa4bc182013-06-30 09:48:50 +00007430
7431 // ... except in the presence of __attribute__((overloadable)).
7432 if (OldDecl->hasAttr<OverloadableAttr>()) {
7433 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7434 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7435 << Redeclaration << NewFD;
7436 Diag(Previous.getFoundDecl()->getLocation(),
7437 diag::note_attribute_overloadable_prev_overload);
7438 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7439 Context));
7440 }
7441 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7442 Redeclaration = false;
7443 OldDecl = 0;
7444 }
7445 }
7446 }
7447 }
7448
Richard Smith21c8fa82013-01-14 05:37:29 +00007449 // C++11 [dcl.constexpr]p8:
7450 // A constexpr specifier for a non-static member function that is not
7451 // a constructor declares that member function to be const.
7452 //
7453 // This needs to be delayed until we know whether this is an out-of-line
7454 // definition of a static member function.
Richard Smith84046262013-04-21 01:08:50 +00007455 //
7456 // This rule is not present in C++1y, so we produce a backwards
7457 // compatibility warning whenever it happens in C++11.
Richard Smith21c8fa82013-01-14 05:37:29 +00007458 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith84046262013-04-21 01:08:50 +00007459 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7460 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith21c8fa82013-01-14 05:37:29 +00007461 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7462 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7463 if (FunctionTemplateDecl *OldTD =
7464 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7465 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7466 if (!OldMD || !OldMD->isStatic()) {
7467 const FunctionProtoType *FPT =
7468 MD->getType()->castAs<FunctionProtoType>();
7469 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7470 EPI.TypeQuals |= Qualifiers::Const;
7471 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00007472 FPT->getArgTypes(), EPI));
Richard Smith84046262013-04-21 01:08:50 +00007473
7474 // Warn that we did this, if we're not performing template instantiation.
7475 // In that case, we'll have warned already when the template was defined.
7476 if (ActiveTemplateInstantiations.empty()) {
7477 SourceLocation AddConstLoc;
7478 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7479 .IgnoreParens().getAs<FunctionTypeLoc>())
7480 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7481
7482 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7483 << FixItHint::CreateInsertion(AddConstLoc, " const");
7484 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007485 }
7486 }
7487
7488 if (Redeclaration) {
7489 // NewFD and OldDecl represent declarations that need to be
7490 // merged.
Richard Smithdd9459f2013-08-13 18:18:50 +00007491 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith21c8fa82013-01-14 05:37:29 +00007492 NewFD->setInvalidDecl();
7493 return Redeclaration;
7494 }
7495
7496 Previous.clear();
7497 Previous.addDecl(OldDecl);
7498
7499 if (FunctionTemplateDecl *OldTemplateDecl
7500 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7501 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7502 FunctionTemplateDecl *NewTemplateDecl
7503 = NewFD->getDescribedFunctionTemplate();
7504 assert(NewTemplateDecl && "Template/non-template mismatch");
7505 if (CXXMethodDecl *Method
7506 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7507 Method->setAccess(OldTemplateDecl->getAccess());
7508 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007509 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007510
7511 // If this is an explicit specialization of a member that is a function
7512 // template, mark it as a member specialization.
7513 if (IsExplicitSpecialization &&
7514 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7515 NewTemplateDecl->setMemberSpecialization();
7516 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00007517 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007518
7519 } else {
John McCalld5617ee2013-01-25 22:31:03 +00007520 // This needs to happen first so that 'inline' propagates.
Richard Smith21c8fa82013-01-14 05:37:29 +00007521 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCalld5617ee2013-01-25 22:31:03 +00007522
7523 if (isa<CXXMethodDecl>(NewFD)) {
7524 // A valid redeclaration of a C++ method must be out-of-line,
7525 // but (unfortunately) it's not necessarily a definition
7526 // because of templates, which means that the previous
7527 // declaration is not necessarily from the class definition.
7528
7529 // For just setting the access, that doesn't matter.
7530 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7531 NewFD->setAccess(oldMethod->getAccess());
7532
7533 // Update the key-function state if necessary for this ABI.
7534 if (NewFD->isInlined() &&
7535 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7536 // setNonKeyFunction needs to work with the original
7537 // declaration from the class definition, and isVirtual() is
7538 // just faster in that case, so map back to that now.
Rafael Espindolabc650912013-10-17 15:37:26 +00007539 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCalld5617ee2013-01-25 22:31:03 +00007540 if (oldMethod->isVirtual()) {
7541 Context.setNonKeyFunction(oldMethod);
7542 }
7543 }
7544 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007545 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00007546 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007547
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007548 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00007549 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007550 // C++-specific checks.
7551 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7552 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00007553 } else if (CXXDestructorDecl *Destructor =
7554 dyn_cast<CXXDestructorDecl>(NewFD)) {
7555 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007556 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00007557
Douglas Gregor4923aa22010-07-02 20:37:36 +00007558 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00007559 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007560 if (!ClassType->isDependentType()) {
7561 DeclarationName Name
7562 = Context.DeclarationNames.getCXXDestructorName(
7563 Context.getCanonicalType(ClassType));
7564 if (NewFD->getDeclName() != Name) {
7565 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007566 NewFD->setInvalidDecl();
7567 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007568 }
7569 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007570 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00007571 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007572 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00007573 }
7574
7575 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00007576 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7577 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00007578 !Method->getDescribedFunctionTemplate() &&
7579 Method->isCanonicalDecl()) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007580 if (AddOverriddenMethods(Method->getParent(), Method)) {
7581 // If the function was marked as "static", we have a problem.
7582 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie5708c182012-10-17 00:47:58 +00007583 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007584 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00007585 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007586 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007587
7588 if (Method->isStatic())
7589 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00007590 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007591
7592 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7593 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007594 CheckOverloadedOperatorDeclaration(NewFD)) {
7595 NewFD->setInvalidDecl();
7596 return Redeclaration;
7597 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007598
7599 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7600 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007601 CheckLiteralOperatorDeclaration(NewFD)) {
7602 NewFD->setInvalidDecl();
7603 return Redeclaration;
7604 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007605
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007606 // In C++, check default arguments now that we have merged decls. Unless
7607 // the lexical context is the class, because in this case this is done
7608 // during delayed parsing anyway.
7609 if (!CurContext->isRecord())
7610 CheckCXXDefaultArguments(NewFD);
Douglas Gregorb68e3992010-12-21 19:47:46 +00007611
7612 // If this function declares a builtin function, check the type of this
7613 // declaration against the expected type for the builtin.
7614 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7615 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanian9ef15182013-01-05 21:54:55 +00007616 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregorb68e3992010-12-21 19:47:46 +00007617 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7618 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7619 // The type of this function differs from the type of the builtin,
7620 // so forget about the builtin entirely.
7621 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7622 }
7623 }
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007624
7625 // If this function is declared as being extern "C", then check to see if
7626 // the function returns a UDT (class, struct, or union type) that is not C
7627 // compatible, and if it does, warn the user.
Fariborz Jahanian96db3292013-03-14 23:09:00 +00007628 // But, issue any diagnostic on the first declaration only.
7629 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007630 QualType R = NewFD->getResultType();
Hans Wennborg168c07b2012-07-24 17:59:41 +00007631 if (R->isIncompleteType() && !R->isVoidType())
7632 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7633 << NewFD << R;
Douglas Gregorb38b4912012-08-07 06:14:34 +00007634 else if (!R.isPODType(Context) && !R->isVoidType() &&
7635 !R->isObjCObjectPointerType())
Hans Wennborg168c07b2012-07-24 17:59:41 +00007636 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007637 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007638 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007639 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007640}
7641
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007642static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7643 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7644 if (!TSI)
7645 return SourceRange();
7646
7647 TypeLoc TL = TSI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00007648 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007649 if (!FunctionTL)
7650 return SourceRange();
7651
David Blaikie39e6ab42013-02-18 22:06:02 +00007652 TypeLoc ResultTL = FunctionTL.getResultLoc();
7653 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007654 return ResultTL.getSourceRange();
7655
7656 return SourceRange();
7657}
7658
David Blaikie14068e82011-09-08 06:33:04 +00007659void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00007660 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7661 // static or constexpr is ill-formed.
Richard Smithde03c152013-01-17 22:16:11 +00007662 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7663 // appear in a declaration of main.
John McCall13591ed2009-07-25 04:36:53 +00007664 // static main is not an error under C99, but we should warn about it.
Richard Smithde03c152013-01-17 22:16:11 +00007665 // We accept _Noreturn main as an extension.
David Blaikie14068e82011-09-08 06:33:04 +00007666 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00007667 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00007668 ? diag::err_static_main : diag::warn_static_main)
7669 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7670 if (FD->isInlineSpecified())
7671 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7672 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko445743d2013-01-21 11:25:03 +00007673 if (DS.isNoreturnSpecified()) {
7674 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7675 SourceRange NoreturnRange(NoreturnLoc,
7676 PP.getLocForEndOfToken(NoreturnLoc));
7677 Diag(NoreturnLoc, diag::ext_noreturn_main);
7678 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7679 << FixItHint::CreateRemoval(NoreturnRange);
7680 }
Richard Smitha5065862012-02-04 06:10:17 +00007681 if (FD->isConstexpr()) {
7682 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7683 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7684 FD->setConstexpr(false);
7685 }
John McCall13591ed2009-07-25 04:36:53 +00007686
7687 QualType T = FD->getType();
7688 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00007689 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007690
John McCall75d8ba32012-02-14 19:50:52 +00007691 // All the standards say that main() should should return 'int'.
7692 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7693 // In C and C++, main magically returns 0 if you fall off the end;
7694 // set the flag which tells us that.
7695 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7696 FD->setHasImplicitReturnZero(true);
7697
7698 // In C with GNU extensions we allow main() to have non-integer return
7699 // type, but we should warn about the extension, and we disable the
7700 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00007701 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00007702 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7703
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007704 SourceRange ResultRange = getResultSourceRange(FD);
7705 if (ResultRange.isValid())
7706 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7707 << FixItHint::CreateReplacement(ResultRange, "int");
7708
John McCall75d8ba32012-02-14 19:50:52 +00007709 // Otherwise, this is just a flat-out error.
7710 } else {
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007711 SourceRange ResultRange = getResultSourceRange(FD);
7712 if (ResultRange.isValid())
7713 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7714 << FixItHint::CreateReplacement(ResultRange, "int");
7715 else
7716 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7717
John McCall13591ed2009-07-25 04:36:53 +00007718 FD->setInvalidDecl(true);
7719 }
7720
7721 // Treat protoless main() as nullary.
7722 if (isa<FunctionNoProtoType>(FT)) return;
7723
7724 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7725 unsigned nparams = FTP->getNumArgs();
7726 assert(FD->getNumParams() == nparams);
7727
John McCall66755862009-12-24 09:58:38 +00007728 bool HasExtraParameters = (nparams > 3);
7729
7730 // Darwin passes an undocumented fourth argument of type char**. If
7731 // other platforms start sprouting these, the logic below will start
7732 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007733 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00007734 HasExtraParameters = false;
7735
7736 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00007737 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7738 FD->setInvalidDecl(true);
7739 nparams = 3;
7740 }
7741
7742 // FIXME: a lot of the following diagnostics would be improved
7743 // if we had some location information about types.
7744
7745 QualType CharPP =
7746 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00007747 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00007748
7749 for (unsigned i = 0; i < nparams; ++i) {
7750 QualType AT = FTP->getArgType(i);
7751
7752 bool mismatch = true;
7753
7754 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7755 mismatch = false;
7756 else if (Expected[i] == CharPP) {
7757 // As an extension, the following forms are okay:
7758 // char const **
7759 // char const * const *
7760 // char * const *
7761
John McCall0953e762009-09-24 19:53:00 +00007762 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00007763 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00007764 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7765 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith485b3122013-01-29 02:49:47 +00007766 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7767 Context.CharTy)) {
John McCall13591ed2009-07-25 04:36:53 +00007768 qs.removeConst();
7769 mismatch = !qs.empty();
7770 }
7771 }
7772
7773 if (mismatch) {
7774 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7775 // TODO: suggest replacing given type with expected type
7776 FD->setInvalidDecl(true);
7777 }
7778 }
7779
7780 if (nparams == 1 && !FD->isInvalidDecl()) {
7781 Diag(FD->getLocation(), diag::warn_main_one_arg);
7782 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007783
7784 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemere9f6f332013-09-16 22:44:20 +00007785 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7786 FD->setInvalidDecl();
7787 }
7788}
7789
7790void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7791 QualType T = FD->getType();
7792 assert(T->isFunctionType() && "function decl is not of function type");
7793 const FunctionType *FT = T->castAs<FunctionType>();
7794
7795 // Set an implicit return of 'zero' if the function can return some integral,
7796 // enumeration, pointer or nullptr type.
7797 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7798 FT->getResultType()->isAnyPointerType() ||
7799 FT->getResultType()->isNullPtrType())
7800 // DllMain is exempt because a return value of zero means it failed.
7801 if (FD->getName() != "DllMain")
7802 FD->setHasImplicitReturnZero(true);
7803
7804 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7805 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007806 FD->setInvalidDecl();
7807 }
John McCall8c4859a2009-07-24 03:03:21 +00007808}
7809
Eli Friedmanc594b322008-05-20 13:48:25 +00007810bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007811 // FIXME: Need strict checking. In C89, we need to check for
7812 // any assignment, increment, decrement, function-calls, or
7813 // commas outside of a sizeof. In C99, it's the same list,
7814 // except that the aforementioned are allowed in unevaluated
7815 // expressions. Everything else falls under the
7816 // "may accept other forms of constant expressions" exception.
7817 // (We never end up here for C++, so the constant expression
7818 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00007819 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00007820 return false;
Eli Friedman21298282009-02-26 04:47:58 +00007821 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7822 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00007823 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00007824}
7825
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007826namespace {
7827 // Visits an initialization expression to see if OrigDecl is evaluated in
7828 // its own initialization and throws a warning if it does.
7829 class SelfReferenceChecker
7830 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7831 Sema &S;
7832 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00007833 bool isRecordType;
7834 bool isPODType;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007835 bool isReferenceType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007836
7837 public:
7838 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7839
7840 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00007841 S(S), OrigDecl(OrigDecl) {
7842 isPODType = false;
7843 isRecordType = false;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007844 isReferenceType = false;
Richard Trieu898267f2011-09-01 21:44:13 +00007845 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7846 isPODType = VD->getType().isPODType(S.Context);
7847 isRecordType = VD->getType()->isRecordType();
Hans Wennborg8be9e772012-08-17 10:12:33 +00007848 isReferenceType = VD->getType()->isReferenceType();
Richard Trieu898267f2011-09-01 21:44:13 +00007849 }
7850 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007851
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007852 // For most expressions, the cast is directly above the DeclRefExpr.
7853 // For conditional operators, the cast can be outside the conditional
7854 // operator if both expressions are DeclRefExpr's.
7855 void HandleValue(Expr *E) {
Richard Trieu568f7852012-10-01 17:39:51 +00007856 if (isReferenceType)
7857 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007858 E = E->IgnoreParenImpCasts();
7859 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7860 HandleDeclRefExpr(DRE);
7861 return;
7862 }
7863
7864 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7865 HandleValue(CO->getTrueExpr());
7866 HandleValue(CO->getFalseExpr());
Richard Trieu6b2cc422012-10-03 00:41:36 +00007867 return;
7868 }
7869
7870 if (isa<MemberExpr>(E)) {
7871 Expr *Base = E->IgnoreParenImpCasts();
7872 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7873 // Check for static member variables and don't warn on them.
7874 if (!isa<FieldDecl>(ME->getMemberDecl()))
7875 return;
7876 Base = ME->getBase()->IgnoreParenImpCasts();
7877 }
7878 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7879 HandleDeclRefExpr(DRE);
7880 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007881 }
7882 }
7883
Richard Trieu568f7852012-10-01 17:39:51 +00007884 // Reference types are handled here since all uses of references are
7885 // bad, not just r-value uses.
7886 void VisitDeclRefExpr(DeclRefExpr *E) {
7887 if (isReferenceType)
7888 HandleDeclRefExpr(E);
7889 }
7890
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007891 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu6b2cc422012-10-03 00:41:36 +00007892 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007893 (isRecordType && E->getCastKind() == CK_NoOp))
7894 HandleValue(E->getSubExpr());
7895
7896 Inherited::VisitImplicitCastExpr(E);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007897 }
7898
Richard Trieu898267f2011-09-01 21:44:13 +00007899 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007900 // Don't warn on arrays since they can be treated as pointers.
Richard Trieu47eb8982011-09-07 00:58:53 +00007901 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007902
Richard Trieu6b2cc422012-10-03 00:41:36 +00007903 // Warn when a non-static method call is followed by non-static member
7904 // field accesses, which is followed by a DeclRefExpr.
7905 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7906 bool Warn = (MD && !MD->isStatic());
7907 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7908 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7909 if (!isa<FieldDecl>(ME->getMemberDecl()))
7910 Warn = false;
7911 Base = ME->getBase()->IgnoreParenImpCasts();
7912 }
Richard Trieu898267f2011-09-01 21:44:13 +00007913
Richard Trieu6b2cc422012-10-03 00:41:36 +00007914 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7915 if (Warn)
7916 HandleDeclRefExpr(DRE);
7917 return;
7918 }
7919
7920 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7921 // Visit that expression.
7922 Visit(Base);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007923 }
7924
Richard Trieu8af742a2013-03-26 03:41:40 +00007925 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7926 if (E->getNumArgs() > 0)
7927 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7928 HandleDeclRefExpr(DRE);
7929
7930 Inherited::VisitCXXOperatorCallExpr(E);
7931 }
7932
Richard Trieu898267f2011-09-01 21:44:13 +00007933 void VisitUnaryOperator(UnaryOperator *E) {
7934 // For POD record types, addresses of its own members are well-defined.
Richard Trieu6b2cc422012-10-03 00:41:36 +00007935 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7936 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7937 if (!isPODType)
7938 HandleValue(E->getSubExpr());
7939 return;
7940 }
Richard Trieu898267f2011-09-01 21:44:13 +00007941 Inherited::VisitUnaryOperator(E);
Richard Smith0f2fc5f2013-05-03 19:16:22 +00007942 }
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007943
7944 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7945
Richard Trieu898267f2011-09-01 21:44:13 +00007946 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumif3052792013-01-19 01:54:35 +00007947 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007948 if (OrigDecl != ReferenceDecl) return;
Ted Kremenek39371b82013-01-19 04:33:14 +00007949 unsigned diag;
7950 if (isReferenceType) {
7951 diag = diag::warn_uninit_self_reference_in_reference_init;
7952 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7953 diag = diag::warn_static_self_reference_in_init;
7954 } else {
7955 diag = diag::warn_uninit_self_reference_in_init;
7956 }
7957
Richard Trieu898267f2011-09-01 21:44:13 +00007958 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborg5965b7c2012-08-20 08:52:22 +00007959 S.PDiag(diag)
Hans Wennborg7821e072012-09-21 08:58:33 +00007960 << DRE->getNameInfo().getName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00007961 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00007962 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007963 }
7964 };
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007965
Richard Trieu568f7852012-10-01 17:39:51 +00007966 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7967 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7968 bool DirectInit) {
7969 // Parameters arguments are occassionially constructed with itself,
7970 // for instance, in recursive functions. Skip them.
7971 if (isa<ParmVarDecl>(OrigDecl))
7972 return;
7973
7974 E = E->IgnoreParens();
7975
7976 // Skip checking T a = a where T is not a record or reference type.
7977 // Doing so is a way to silence uninitialized warnings.
7978 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7979 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7980 if (ICE->getCastKind() == CK_LValueToRValue)
7981 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7982 if (DRE->getDecl() == OrigDecl)
7983 return;
7984
7985 SelfReferenceChecker(S, OrigDecl).Visit(E);
7986 }
Richard Trieu898267f2011-09-01 21:44:13 +00007987}
7988
Douglas Gregor09f41cf2009-01-14 15:45:31 +00007989/// AddInitializerToDecl - Adds the initializer Init to the
7990/// declaration dcl. If DirectInit is true, this is C++ direct
7991/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00007992void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
7993 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00007994 // If there is no declaration, there was an error parsing it. Just ignore
7995 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00007996 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00007997 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007998
Douglas Gregor021c3b32009-03-11 23:00:04 +00007999 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8000 // With declarators parsed the way they are, the parser cannot
8001 // distinguish between a normal initializer and a pure-specifier.
8002 // Thus this grotesque test.
8003 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00008004 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00008005 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8006 CheckPureMethod(Method, Init->getSourceRange());
8007 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00008008 Diag(Method->getLocation(), diag::err_member_function_initialization)
8009 << Method->getDeclName() << Init->getSourceRange();
8010 Method->setInvalidDecl();
8011 }
8012 return;
8013 }
8014
Steve Naroff410e3e22007-09-12 20:13:48 +00008015 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8016 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00008017 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8018 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00008019 RealDecl->setInvalidDecl();
8020 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00008021 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008022 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8023
Richard Smith01888722011-12-15 19:20:59 +00008024 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00008025 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008026 Expr *DeduceInit = Init;
8027 // Initializer could be a C++ direct-initializer. Deduction only works if it
8028 // contains exactly one expression.
8029 if (CXXDirectInit) {
8030 if (CXXDirectInit->getNumExprs() == 0) {
8031 // It isn't possible to write this directly, but it is possible to
8032 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00008033 Diag(CXXDirectInit->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008034 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8035 : diag::err_auto_var_init_no_expression)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008036 << VDecl->getDeclName() << VDecl->getType()
8037 << VDecl->getSourceRange();
8038 RealDecl->setInvalidDecl();
8039 return;
8040 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00008041 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008042 VDecl->isInitCapture()
8043 ? diag::err_init_capture_multiple_expressions
8044 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008045 << VDecl->getDeclName() << VDecl->getType()
8046 << VDecl->getSourceRange();
8047 RealDecl->setInvalidDecl();
8048 return;
8049 } else {
8050 DeduceInit = CXXDirectInit->getExpr(0);
8051 }
8052 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008053
8054 // Expressions default to 'id' when we're in a debugger.
8055 bool DefaultedToAuto = false;
8056 if (getLangOpts().DebuggerCastResultToId &&
8057 Init->getType() == Context.UnknownAnyTy) {
8058 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8059 if (Result.isInvalid()) {
8060 VDecl->setInvalidDecl();
8061 return;
8062 }
8063 Init = Result.take();
8064 DefaultedToAuto = true;
8065 }
Richard Smith9b131752013-04-30 21:23:01 +00008066
8067 QualType DeducedType;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008068 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00008069 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008070 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9b131752013-04-30 21:23:01 +00008071 if (DeducedType.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008072 RealDecl->setInvalidDecl();
8073 return;
8074 }
Richard Smith9b131752013-04-30 21:23:01 +00008075 VDecl->setType(DeducedType);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00008076 assert(VDecl->isLinkageValid());
Rafael Espindola2d9e8832013-03-12 21:06:00 +00008077
John McCallf85e1932011-06-15 23:02:42 +00008078 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00008079 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00008080 VDecl->setInvalidDecl();
8081
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008082 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8083 // 'id' instead of a specific object type prevents most of our usual checks.
8084 // We only want to warn outside of template instantiations, though:
8085 // inside a template, the 'id' could have come from a parameter.
Douglas Gregor1344e942013-03-07 22:57:58 +00008086 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith9b131752013-04-30 21:23:01 +00008087 DeducedType->isObjCIdType()) {
8088 SourceLocation Loc =
8089 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008090 Diag(Loc, diag::warn_auto_var_is_id)
8091 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8092 }
8093
Richard Smith34b41d92011-02-20 03:19:35 +00008094 // If this is a redeclaration, check that the type we just deduced matches
8095 // the previously declared type.
Richard Smithdd9459f2013-08-13 18:18:50 +00008096 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8097 // We never need to merge the type, because we cannot form an incomplete
8098 // array of auto, nor deduce such a type.
8099 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8100 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00008101
8102 // Check the deduced type is valid for a variable declaration.
8103 CheckVariableDeclarationType(VDecl);
8104 if (VDecl->isInvalidDecl())
8105 return;
Richard Smith34b41d92011-02-20 03:19:35 +00008106 }
Richard Smith01888722011-12-15 19:20:59 +00008107
8108 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8109 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8110 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8111 VDecl->setInvalidDecl();
8112 return;
8113 }
8114
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008115 if (!VDecl->getType()->isDependentType()) {
8116 // A definition must end up with a complete type, which means it must be
8117 // complete with the restriction that an array type might be completed by
8118 // the initializer; note that later code assumes this restriction.
8119 QualType BaseDeclType = VDecl->getType();
8120 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8121 BaseDeclType = Array->getElementType();
8122 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8123 diag::err_typecheck_decl_incomplete_type)) {
8124 RealDecl->setInvalidDecl();
8125 return;
8126 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008127
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008128 // The variable can not have an abstract class type.
8129 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8130 diag::err_abstract_type_in_decl,
8131 AbstractVariableType))
8132 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00008133 }
8134
Sebastian Redl31310a22010-02-01 20:16:42 +00008135 const VarDecl *Def;
8136 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00008137 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00008138 << VDecl->getDeclName();
8139 Diag(Def->getLocation(), diag::note_previous_definition);
8140 VDecl->setInvalidDecl();
8141 return;
8142 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008143
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008144 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00008145 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00008146 // C++ [class.static.data]p4
8147 // If a static data member is of const integral or const
8148 // enumeration type, its declaration in the class definition can
8149 // specify a constant-initializer which shall be an integral
8150 // constant expression (5.19). In that case, the member can appear
8151 // in integral constant expressions. The member shall still be
8152 // defined in a namespace scope if it is used in the program and the
8153 // namespace scope definition shall not contain an initializer.
8154 //
8155 // We already performed a redefinition check above, but for static
8156 // data members we also need to check whether there was an in-class
8157 // declaration with an initializer.
8158 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00008159 Diag(VDecl->getLocation(), diag::err_redefinition)
8160 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00008161 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8162 return;
8163 }
Douglas Gregor275a3692009-03-10 23:43:53 +00008164
Douglas Gregora31040f2010-12-16 01:31:22 +00008165 if (VDecl->hasLocalStorage())
8166 getCurFunction()->setHasBranchProtectedScope();
8167
8168 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8169 VDecl->setInvalidDecl();
8170 return;
8171 }
8172 }
John McCalle46f62c2010-08-01 01:24:59 +00008173
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008174 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8175 // a kernel function cannot be initialized."
8176 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8177 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8178 VDecl->setInvalidDecl();
8179 return;
8180 }
8181
Steve Naroffbb204692007-09-12 14:07:44 +00008182 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00008183 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00008184 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008185
Douglas Gregor1344e942013-03-07 22:57:58 +00008186 // Expressions default to 'id' when we're in a debugger
8187 // and we are assigning it to a variable of Objective-C pointer type.
8188 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8189 Init->getType() == Context.UnknownAnyTy) {
8190 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8191 if (Result.isInvalid()) {
8192 VDecl->setInvalidDecl();
8193 return;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008194 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008195 Init = Result.take();
8196 }
Richard Smith01888722011-12-15 19:20:59 +00008197
8198 // Perform the initialization.
8199 if (!VDecl->isInvalidDecl()) {
8200 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8201 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00008202 = DirectInit ?
8203 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8204 Init->getLocStart(),
8205 Init->getLocEnd())
8206 : InitializationKind::CreateDirectList(
8207 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00008208 : InitializationKind::CreateCopy(VDecl->getLocation(),
8209 Init->getLocStart());
8210
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008211 MultiExprArg Args = Init;
8212 if (CXXDirectInit)
8213 Args = MultiExprArg(CXXDirectInit->getExprs(),
8214 CXXDirectInit->getNumExprs());
8215
8216 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8217 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith01888722011-12-15 19:20:59 +00008218 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00008219 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00008220 return;
Steve Naroffbb204692007-09-12 14:07:44 +00008221 }
Richard Smith01888722011-12-15 19:20:59 +00008222
8223 Init = Result.takeAs<Expr>();
8224 }
8225
Richard Trieu568f7852012-10-01 17:39:51 +00008226 // Check for self-references within variable initializers.
8227 // Variables declared within a function/method body (except for references)
8228 // are handled by a dataflow analysis.
8229 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8230 VDecl->getType()->isReferenceType()) {
8231 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8232 }
8233
Richard Smith01888722011-12-15 19:20:59 +00008234 // If the type changed, it means we had an incomplete type that was
8235 // completed by the initializer. For example:
8236 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00008237 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00008238 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00008239 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00008240
Jordan Rosee10f4d32012-09-15 02:48:31 +00008241 if (!VDecl->isInvalidDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00008242 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8243
Jordan Rosee10f4d32012-09-15 02:48:31 +00008244 if (VDecl->hasAttr<BlocksAttr>())
8245 checkRetainCycles(VDecl, Init);
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008246
8247 // It is safe to assign a weak reference into a strong variable.
8248 // Although this code can still have problems:
8249 // id x = self.weakProp;
8250 // id y = self.weakProp;
8251 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8252 // paths through the function. This should be revisited if
8253 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek904a3262012-12-20 22:31:27 +00008254 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008255 DiagnosticsEngine::Level Level =
8256 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8257 Init->getLocStart());
8258 if (Level != DiagnosticsEngine::Ignored)
8259 getCurFunction()->markSafeWeakUse(Init);
8260 }
Jordan Rosee10f4d32012-09-15 02:48:31 +00008261 }
8262
Richard Smith41956372013-01-14 22:39:08 +00008263 // The initialization is usually a full-expression.
8264 //
8265 // FIXME: If this is a braced initialization of an aggregate, it is not
8266 // an expression, and each individual field initializer is a separate
8267 // full-expression. For instance, in:
8268 //
8269 // struct Temp { ~Temp(); };
8270 // struct S { S(Temp); };
8271 // struct T { S a, b; } t = { Temp(), Temp() }
8272 //
8273 // we should destroy the first Temp before constructing the second.
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008274 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8275 false,
8276 VDecl->isConstexpr());
Richard Smith41956372013-01-14 22:39:08 +00008277 if (Result.isInvalid()) {
8278 VDecl->setInvalidDecl();
8279 return;
8280 }
8281 Init = Result.take();
8282
Richard Smith01888722011-12-15 19:20:59 +00008283 // Attach the initializer to the decl.
8284 VDecl->setInit(Init);
8285
8286 if (VDecl->isLocalVarDecl()) {
8287 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8288 // static storage duration shall be constant expressions or string literals.
8289 // C++ does not have this restriction.
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008290 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8291 if (VDecl->getStorageClass() == SC_Static)
8292 CheckForConstantInitializer(Init, DclT);
8293 // C89 is stricter than C99 for non-static aggregate types.
8294 // C89 6.5.7p3: All the expressions [...] in an initializer list
8295 // for an object that has aggregate or union type shall be
8296 // constant expressions.
8297 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanella82026302013-07-22 19:10:20 +00008298 isa<InitListExpr>(Init) &&
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008299 !Init->isConstantInitializer(Context, false))
8300 Diag(Init->getExprLoc(),
8301 diag::ext_aggregate_init_not_constant)
8302 << Init->getSourceRange();
8303 }
Mike Stump1eb44332009-09-09 15:08:12 +00008304 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00008305 VDecl->getLexicalDeclContext()->isRecord()) {
8306 // This is an in-class initialization for a static data member, e.g.,
8307 //
8308 // struct S {
8309 // static const int value = 17;
8310 // };
8311
Douglas Gregor021c3b32009-03-11 23:00:04 +00008312 // C++ [class.mem]p4:
8313 // A member-declarator can contain a constant-initializer only
8314 // if it declares a static member (9.4) of const integral or
8315 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00008316 //
Richard Smith01888722011-12-15 19:20:59 +00008317 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00008318 // If a non-volatile const static data member is of integral or
8319 // enumeration type, its declaration in the class definition can
8320 // specify a brace-or-equal-initializer in which every initalizer-clause
8321 // that is an assignment-expression is a constant expression. A static
8322 // data member of literal type can be declared in the class definition
8323 // with the constexpr specifier; if so, its declaration shall specify a
8324 // brace-or-equal-initializer in which every initializer-clause that is
8325 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00008326
8327 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00008328 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00008329
Richard Smithc6d990a2011-09-29 19:11:37 +00008330 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00008331 // type. We separately check that every constexpr variable is of literal
8332 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00008333 } else if (VDecl->isConstexpr()) {
8334
John McCall4e635642010-09-10 23:21:22 +00008335 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00008336 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00008337 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8338 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008339 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008340
8341 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00008342 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00008343 // Check whether the expression is a constant expression.
8344 SourceLocation Loc;
Richard Smith80ad52f2013-01-02 11:42:31 +00008345 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00008346 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00008347 // in-class initializer cannot be volatile.
8348 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8349 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00008350 ; // Nothing to check.
8351 else if (Init->isIntegerConstantExpr(Context, &Loc))
8352 ; // Ok, it's an ICE!
8353 else if (Init->isEvaluatable(Context)) {
8354 // If we can constant fold the initializer through heroics, accept it,
8355 // but report this as a use of an extension for -pedantic.
8356 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8357 << Init->getSourceRange();
8358 } else {
8359 // Otherwise, this is some crazy unknown case. Report the issue at the
8360 // location provided by the isIntegerConstantExpr failed check.
8361 Diag(Loc, diag::err_in_class_initializer_non_constant)
8362 << Init->getSourceRange();
8363 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008364 }
8365
Richard Smith01888722011-12-15 19:20:59 +00008366 // We allow foldable floating-point constants as an extension.
8367 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithb4b1d692013-01-25 04:22:16 +00008368 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8369 // it anyway and provide a fixit to add the 'constexpr'.
8370 if (getLangOpts().CPlusPlus11) {
David Blaikiea367e9d2013-01-29 22:26:08 +00008371 Diag(VDecl->getLocation(),
8372 diag::ext_in_class_initializer_float_type_cxx11)
8373 << DclT << Init->getSourceRange();
8374 Diag(VDecl->getLocStart(),
8375 diag::note_in_class_initializer_float_type_cxx11)
8376 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithb4b1d692013-01-25 04:22:16 +00008377 } else {
8378 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8379 << DclT << Init->getSourceRange();
John McCall4e635642010-09-10 23:21:22 +00008380
Richard Smithb4b1d692013-01-25 04:22:16 +00008381 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8382 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8383 << Init->getSourceRange();
8384 VDecl->setInvalidDecl();
8385 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00008386 }
Richard Smith947be192011-09-29 23:18:34 +00008387
Richard Smith01888722011-12-15 19:20:59 +00008388 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smitha10b9782013-04-22 15:31:51 +00008389 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith947be192011-09-29 23:18:34 +00008390 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00008391 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00008392 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8393 VDecl->setConstexpr(true);
8394
Richard Smithc6d990a2011-09-29 19:11:37 +00008395 } else {
8396 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00008397 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00008398 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008399 }
Steve Naroff248a7532008-04-15 22:42:06 +00008400 } else if (VDecl->isFileVarDecl()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008401 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008402 (!getLangOpts().CPlusPlus ||
Rafael Espindola5b34b9c2013-03-29 07:56:05 +00008403 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smithd0629eb2013-09-27 20:14:12 +00008404 VDecl->isExternC())) &&
8405 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff410e3e22007-09-12 20:13:48 +00008406 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00008407
Richard Smith01888722011-12-15 19:20:59 +00008408 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00008409 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00008410 CheckForConstantInitializer(Init, DclT);
Richard Smith6a570f62013-04-14 20:11:31 +00008411 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8412 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8413 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smithb6b127f2013-04-15 08:07:34 +00008414 !Init->isConstantInitializer(
8415 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6a570f62013-04-14 20:11:31 +00008416 // GNU C++98 edits for __thread, [basic.start.init]p4:
8417 // An object of thread storage duration shall not require dynamic
8418 // initialization.
8419 // FIXME: Need strict checking here.
8420 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8421 if (getLangOpts().CPlusPlus11)
8422 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8423 }
Steve Naroffbb204692007-09-12 14:07:44 +00008424 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008425
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008426 // We will represent direct-initialization similarly to copy-initialization:
8427 // int x(1); -as-> int x = 1;
8428 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8429 //
8430 // Clients that want to distinguish between the two forms, can check for
8431 // direct initializer using VarDecl::getInitStyle().
8432 // A major benefit is that clients that don't particularly care about which
8433 // exactly form was it (like the CodeGen) can handle both cases without
8434 // special case code.
8435
8436 // C++ 8.5p11:
8437 // The form of initialization (using parentheses or '=') is generally
8438 // insignificant, but does matter when the entity being initialized has a
8439 // class type.
8440 if (CXXDirectInit) {
8441 assert(DirectInit && "Call-style initializer must be direct init.");
8442 VDecl->setInitStyle(VarDecl::CallInit);
8443 } else if (DirectInit) {
8444 // This must be list-initialization. No other way is direct-initialization.
8445 VDecl->setInitStyle(VarDecl::ListInit);
8446 }
8447
John McCall2998d6b2011-01-19 11:48:09 +00008448 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00008449}
8450
John McCall7727acf2010-03-31 02:13:20 +00008451/// ActOnInitializerError - Given that there was an error parsing an
8452/// initializer for the given declaration, try to return to some form
8453/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00008454void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00008455 // Our main concern here is re-establishing invariants like "a
8456 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00008457 if (!D || D->isInvalidDecl()) return;
8458
8459 VarDecl *VD = dyn_cast<VarDecl>(D);
8460 if (!VD) return;
8461
Richard Smith34b41d92011-02-20 03:19:35 +00008462 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00008463 if (ParsingInitForAutoVars.count(D)) {
8464 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008465 return;
8466 }
8467
John McCall7727acf2010-03-31 02:13:20 +00008468 QualType Ty = VD->getType();
8469 if (Ty->isDependentType()) return;
8470
8471 // Require a complete type.
8472 if (RequireCompleteType(VD->getLocation(),
8473 Context.getBaseElementType(Ty),
8474 diag::err_typecheck_decl_incomplete_type)) {
8475 VD->setInvalidDecl();
8476 return;
8477 }
8478
8479 // Require an abstract type.
8480 if (RequireNonAbstractType(VD->getLocation(), Ty,
8481 diag::err_abstract_type_in_decl,
8482 AbstractVariableType)) {
8483 VD->setInvalidDecl();
8484 return;
8485 }
8486
8487 // Don't bother complaining about constructors or destructors,
8488 // though.
8489}
8490
John McCalld226f652010-08-21 09:40:31 +00008491void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00008492 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00008493 // If there is no declaration, there was an error parsing it. Just ignore it.
8494 if (RealDecl == 0)
8495 return;
8496
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008497 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8498 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008499
Richard Smithdd4b3502011-12-25 21:17:58 +00008500 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00008501 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00008502 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8503 << Var->getDeclName() << Type;
8504 Var->setInvalidDecl();
8505 return;
8506 }
Mike Stump1eb44332009-09-09 15:08:12 +00008507
Richard Smithdd4b3502011-12-25 21:17:58 +00008508 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00008509 // the constexpr specifier; if so, its declaration shall specify
8510 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00008511 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8512 // the definition of a variable [...] or the declaration of a static data
8513 // member.
8514 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8515 if (Var->isStaticDataMember())
8516 Diag(Var->getLocation(),
8517 diag::err_constexpr_static_mem_var_requires_init)
8518 << Var->getDeclName();
8519 else
8520 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00008521 Var->setInvalidDecl();
8522 return;
8523 }
8524
Douglas Gregor60c93c92010-02-09 07:26:29 +00008525 switch (Var->isThisDeclarationADefinition()) {
8526 case VarDecl::Definition:
8527 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8528 break;
8529
8530 // We have an out-of-line definition of a static data member
8531 // that has an in-class initializer, so we type-check this like
8532 // a declaration.
8533 //
8534 // Fall through
8535
8536 case VarDecl::DeclarationOnly:
8537 // It's only a declaration.
8538
8539 // Block scope. C99 6.7p7: If an identifier for an object is
8540 // declared with no linkage (C99 6.2.2p6), the type for the
8541 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00008542 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008543 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00008544 RequireCompleteType(Var->getLocation(), Type,
8545 diag::err_typecheck_decl_incomplete_type))
8546 Var->setInvalidDecl();
8547
8548 // Make sure that the type is not abstract.
8549 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8550 RequireNonAbstractType(Var->getLocation(), Type,
8551 diag::err_abstract_type_in_decl,
8552 AbstractVariableType))
8553 Var->setInvalidDecl();
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008554 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008555 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008556 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008557 Diag(Var->getLocation(), diag::note_private_extern);
8558 }
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008559
Douglas Gregor60c93c92010-02-09 07:26:29 +00008560 return;
8561
8562 case VarDecl::TentativeDefinition:
8563 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8564 // object that has file scope without an initializer, and without a
8565 // storage-class specifier or with the storage-class specifier "static",
8566 // constitutes a tentative definition. Note: A tentative definition with
8567 // external linkage is valid (C99 6.2.2p5).
8568 if (!Var->isInvalidDecl()) {
8569 if (const IncompleteArrayType *ArrayT
8570 = Context.getAsIncompleteArrayType(Type)) {
8571 if (RequireCompleteType(Var->getLocation(),
8572 ArrayT->getElementType(),
8573 diag::err_illegal_decl_array_incomplete_type))
8574 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00008575 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00008576 // C99 6.9.2p3: If the declaration of an identifier for an object is
8577 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8578 // declared type shall not be an incomplete type.
8579 // NOTE: code such as the following
8580 // static struct s;
8581 // struct s { int a; };
8582 // is accepted by gcc. Hence here we issue a warning instead of
8583 // an error and we do not invalidate the static declaration.
8584 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00008585 if (Var->isFirstDecl())
Douglas Gregor60c93c92010-02-09 07:26:29 +00008586 RequireCompleteType(Var->getLocation(), Type,
8587 diag::ext_typecheck_decl_incomplete_type);
8588 }
8589 }
8590
8591 // Record the tentative definition; we're done.
8592 if (!Var->isInvalidDecl())
8593 TentativeDefinitions.push_back(Var);
8594 return;
8595 }
8596
8597 // Provide a specific diagnostic for uninitialized variable
8598 // definitions with incomplete array type.
8599 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00008600 Diag(Var->getLocation(),
8601 diag::err_typecheck_incomplete_array_needs_initializer);
8602 Var->setInvalidDecl();
8603 return;
8604 }
8605
John McCallb567a8b2010-08-01 01:25:24 +00008606 // Provide a specific diagnostic for uninitialized variable
8607 // definitions with reference type.
8608 if (Type->isReferenceType()) {
8609 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8610 << Var->getDeclName()
8611 << SourceRange(Var->getLocation(), Var->getLocation());
8612 Var->setInvalidDecl();
8613 return;
8614 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008615
8616 // Do not attempt to type-check the default initializer for a
8617 // variable with dependent type.
8618 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00008619 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00008620
Douglas Gregor60c93c92010-02-09 07:26:29 +00008621 if (Var->isInvalidDecl())
8622 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00008623
Douglas Gregor60c93c92010-02-09 07:26:29 +00008624 if (RequireCompleteType(Var->getLocation(),
8625 Context.getBaseElementType(Type),
8626 diag::err_typecheck_decl_incomplete_type)) {
8627 Var->setInvalidDecl();
8628 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008629 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008630
Douglas Gregor60c93c92010-02-09 07:26:29 +00008631 // The variable can not have an abstract class type.
8632 if (RequireNonAbstractType(Var->getLocation(), Type,
8633 diag::err_abstract_type_in_decl,
8634 AbstractVariableType)) {
8635 Var->setInvalidDecl();
8636 return;
8637 }
8638
Douglas Gregor4337dc72011-05-21 17:52:48 +00008639 // Check for jumps past the implicit initializer. C++0x
8640 // clarifies that this applies to a "variable with automatic
8641 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00008642 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00008643 // A program that jumps from a point where a variable with automatic
8644 // storage duration is not in scope to a point where it is in scope is
8645 // ill-formed unless the variable has scalar type, class type with a
8646 // trivial default constructor and a trivial destructor, a cv-qualified
8647 // version of one of these types, or an array of one of the preceding
8648 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00008649 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008650 if (const RecordType *Record
8651 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00008652 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00008653 // Mark the function for further checking even if the looser rules of
8654 // C++11 do not require such checks, so that we can diagnose
8655 // incompatibilities with C++98.
8656 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00008657 getCurFunction()->setHasBranchProtectedScope();
8658 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008659 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00008660
8661 // C++03 [dcl.init]p9:
8662 // If no initializer is specified for an object, and the
8663 // object is of (possibly cv-qualified) non-POD class type (or
8664 // array thereof), the object shall be default-initialized; if
8665 // the object is of const-qualified type, the underlying class
8666 // type shall have a user-declared default
8667 // constructor. Otherwise, if no initializer is specified for
8668 // a non- static object, the object and its subobjects, if
8669 // any, have an indeterminate initial value); if the object
8670 // or any of its subobjects are of const-qualified type, the
8671 // program is ill-formed.
8672 // C++0x [dcl.init]p11:
8673 // If no initializer is specified for an object, the object is
8674 // default-initialized; [...].
8675 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8676 InitializationKind Kind
8677 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00008678
8679 InitializationSequence InitSeq(*this, Entity, Kind, None);
8680 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor4337dc72011-05-21 17:52:48 +00008681 if (Init.isInvalid())
8682 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008683 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008684 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008685 // This is important for template substitution.
8686 Var->setInitStyle(VarDecl::CallInit);
8687 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00008688
John McCall2998d6b2011-01-19 11:48:09 +00008689 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008690 }
8691}
8692
Richard Smithad762fc2011-04-14 22:09:26 +00008693void Sema::ActOnCXXForRangeDecl(Decl *D) {
8694 VarDecl *VD = dyn_cast<VarDecl>(D);
8695 if (!VD) {
8696 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8697 D->setInvalidDecl();
8698 return;
8699 }
8700
8701 VD->setCXXForRangeDecl(true);
8702
8703 // for-range-declaration cannot be given a storage class specifier.
8704 int Error = -1;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008705 switch (VD->getStorageClass()) {
Richard Smithad762fc2011-04-14 22:09:26 +00008706 case SC_None:
8707 break;
8708 case SC_Extern:
8709 Error = 0;
8710 break;
8711 case SC_Static:
8712 Error = 1;
8713 break;
8714 case SC_PrivateExtern:
8715 Error = 2;
8716 break;
8717 case SC_Auto:
8718 Error = 3;
8719 break;
8720 case SC_Register:
8721 Error = 4;
8722 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008723 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00008724 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00008725 }
Richard Smithc6d990a2011-09-29 19:11:37 +00008726 if (VD->isConstexpr())
8727 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00008728 if (Error != -1) {
8729 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8730 << VD->getDeclName() << Error;
8731 D->setInvalidDecl();
8732 }
8733}
8734
John McCall2998d6b2011-01-19 11:48:09 +00008735void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8736 if (var->isInvalidDecl()) return;
8737
John McCallf85e1932011-06-15 23:02:42 +00008738 // In ARC, don't allow jumps past the implicit initialization of a
8739 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00008740 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00008741 var->hasLocalStorage()) {
8742 switch (var->getType().getObjCLifetime()) {
8743 case Qualifiers::OCL_None:
8744 case Qualifiers::OCL_ExplicitNone:
8745 case Qualifiers::OCL_Autoreleasing:
8746 break;
8747
8748 case Qualifiers::OCL_Weak:
8749 case Qualifiers::OCL_Strong:
8750 getCurFunction()->setHasBranchProtectedScope();
8751 break;
8752 }
8753 }
8754
Eli Friedmane4851f22012-10-23 20:19:32 +00008755 if (var->isThisDeclarationADefinition() &&
Eli Friedman2ae28e52013-09-24 23:10:08 +00008756 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimekacaf1102012-12-12 13:26:54 +00008757 getDiagnostics().getDiagnosticLevel(
8758 diag::warn_missing_variable_declarations,
8759 var->getLocation())) {
Eli Friedmane4851f22012-10-23 20:19:32 +00008760 // Find a previous declaration that's not a definition.
8761 VarDecl *prev = var->getPreviousDecl();
8762 while (prev && prev->isThisDeclarationADefinition())
8763 prev = prev->getPreviousDecl();
8764
8765 if (!prev)
8766 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8767 }
8768
Richard Smith6a570f62013-04-14 20:11:31 +00008769 if (var->getTLSKind() == VarDecl::TLS_Static &&
8770 var->getType().isDestructedType()) {
8771 // GNU C++98 edits for __thread, [basic.start.term]p3:
8772 // The type of an object with thread storage duration shall not
8773 // have a non-trivial destructor.
8774 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8775 if (getLangOpts().CPlusPlus11)
8776 Diag(var->getLocation(), diag::note_use_thread_local);
8777 }
8778
John McCall2998d6b2011-01-19 11:48:09 +00008779 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00008780 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00008781
Richard Smitha67d5032012-11-09 23:03:14 +00008782 QualType type = var->getType();
8783 if (type->isDependentType()) return;
John McCall2998d6b2011-01-19 11:48:09 +00008784
8785 // __block variables might require us to capture a copy-initializer.
8786 if (var->hasAttr<BlocksAttr>()) {
8787 // It's currently invalid to ever have a __block variable with an
8788 // array type; should we diagnose that here?
8789
8790 // Regardless, we don't want to ignore array nesting when
8791 // constructing this copy.
John McCall2998d6b2011-01-19 11:48:09 +00008792 if (type->isStructureOrClassType()) {
John McCallb760f112013-03-22 02:10:40 +00008793 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall2998d6b2011-01-19 11:48:09 +00008794 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00008795 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregor6cda3e62013-03-07 22:38:24 +00008796 ExprResult result
8797 = PerformMoveOrCopyInitialization(
8798 InitializedEntity::InitializeBlock(poi, type, false),
8799 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall2998d6b2011-01-19 11:48:09 +00008800 if (!result.isInvalid()) {
8801 result = MaybeCreateExprWithCleanups(result);
8802 Expr *init = result.takeAs<Expr>();
8803 Context.setBlockVarCopyInits(var, init);
8804 }
8805 }
8806 }
8807
Richard Smith66f85712011-11-07 22:16:17 +00008808 Expr *Init = var->getInit();
8809 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smitha67d5032012-11-09 23:03:14 +00008810 QualType baseType = Context.getBaseElementType(type);
Richard Smith66f85712011-11-07 22:16:17 +00008811
Richard Smith9568f0c2012-10-29 18:26:47 +00008812 if (!var->getDeclContext()->isDependentContext() &&
8813 Init && !Init->isValueDependent()) {
Richard Smith099e7f62011-12-19 06:19:21 +00008814 if (IsGlobal && !var->isConstexpr() &&
8815 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8816 var->getLocation())
Eli Friedman21cde052013-07-16 22:40:53 +00008817 != DiagnosticsEngine::Ignored) {
8818 // Warn about globals which don't have a constant initializer. Don't
8819 // warn about globals with a non-trivial destructor because we already
8820 // warned about them.
8821 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8822 if (!(RD && !RD->hasTrivialDestructor()) &&
8823 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8824 Diag(var->getLocation(), diag::warn_global_constructor)
8825 << Init->getSourceRange();
8826 }
Richard Smith099e7f62011-12-19 06:19:21 +00008827
Richard Smith099e7f62011-12-19 06:19:21 +00008828 if (var->isConstexpr()) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008829 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00008830 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8831 SourceLocation DiagLoc = var->getLocation();
8832 // If the note doesn't add any useful information other than a source
8833 // location, fold it into the primary diagnostic.
8834 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8835 diag::note_invalid_subexpr_in_const_expr) {
8836 DiagLoc = Notes[0].first;
8837 Notes.clear();
8838 }
8839 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8840 << var << Init->getSourceRange();
8841 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8842 Diag(Notes[I].first, Notes[I].second);
8843 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00008844 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00008845 // Check whether the initializer of a const variable of integral or
8846 // enumeration type is an ICE now, since we can't tell whether it was
8847 // initialized by a constant expression if we check later.
8848 var->checkInitIsICE();
8849 }
Richard Smith66f85712011-11-07 22:16:17 +00008850 }
John McCall2998d6b2011-01-19 11:48:09 +00008851
8852 // Require the destructor.
8853 if (const RecordType *recordType = baseType->getAs<RecordType>())
8854 FinalizeVarWithDestructor(var, recordType);
8855}
8856
Richard Smith483b9f32011-02-21 20:05:19 +00008857/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8858/// any semantic actions necessary after any initializer has been attached.
8859void
8860Sema::FinalizeDeclaration(Decl *ThisDecl) {
8861 // Note that we are no longer parsing the initializer for this declaration.
8862 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008863
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008864 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindolada844b32013-01-03 04:05:19 +00008865 if (!VD)
8866 return;
8867
Rafael Espindola29535ba2013-08-16 23:18:50 +00008868 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8869 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8870 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8871 VD->dropAttr<UsedAttr>();
8872 }
8873 }
8874
Rafael Espindolab1c0e202013-10-22 21:39:03 +00008875 if (!VD->isInvalidDecl() &&
8876 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8877 if (const VarDecl *Def = VD->getDefinition()) {
8878 if (Def->hasAttr<AliasAttr>()) {
8879 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8880 << VD->getDeclName();
8881 Diag(Def->getLocation(), diag::note_previous_definition);
8882 VD->setInvalidDecl();
8883 }
8884 }
8885 }
8886
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008887 const DeclContext *DC = VD->getDeclContext();
8888 // If there's a #pragma GCC visibility in scope, and this isn't a class
8889 // member, set the visibility of this variable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008890 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008891 AddPushedVisibilityAttribute(VD);
8892
Rafael Espindola6769ccb2013-01-03 04:29:20 +00008893 if (VD->isFileVarDecl())
8894 MarkUnusedFileScopedDecl(VD);
8895
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008896 // Now we have parsed the initializer and can update the table of magic
8897 // tag values.
Rafael Espindolada844b32013-01-03 04:05:19 +00008898 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8899 !VD->getType()->isIntegralOrEnumerationType())
8900 return;
8901
8902 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8903 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8904 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8905 I != E; ++I) {
8906 const Expr *MagicValueExpr = VD->getInit();
8907 if (!MagicValueExpr) {
8908 continue;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008909 }
Rafael Espindolada844b32013-01-03 04:05:19 +00008910 llvm::APSInt MagicValueInt;
8911 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8912 Diag(I->getRange().getBegin(),
8913 diag::err_type_tag_for_datatype_not_ice)
8914 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8915 continue;
8916 }
8917 if (MagicValueInt.getActiveBits() > 64) {
8918 Diag(I->getRange().getBegin(),
8919 diag::err_type_tag_for_datatype_too_large)
8920 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8921 continue;
8922 }
8923 uint64_t MagicValue = MagicValueInt.getZExtValue();
8924 RegisterTypeTagForDatatype(I->getArgumentKind(),
8925 MagicValue,
8926 I->getMatchingCType(),
8927 I->getLayoutCompatible(),
8928 I->getMustBeNull());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008929 }
Richard Smith483b9f32011-02-21 20:05:19 +00008930}
8931
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008932Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8933 ArrayRef<Decl *> Group) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00008934 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008935
8936 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00008937 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008938
David Majnemeraa824612013-09-17 23:57:10 +00008939 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008940 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemeraa824612013-09-17 23:57:10 +00008941 if (Decl *D = Group[i]) {
8942 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8943 if (!FirstDeclaratorInGroup)
8944 FirstDeclaratorInGroup = DD;
Richard Smith406c38e2011-02-23 00:37:57 +00008945 Decls.push_back(D);
David Majnemeraa824612013-09-17 23:57:10 +00008946 }
Richard Smith406c38e2011-02-23 00:37:57 +00008947
Eli Friedman5e867c82013-07-10 00:30:46 +00008948 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemeraa824612013-09-17 23:57:10 +00008949 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman5e867c82013-07-10 00:30:46 +00008950 HandleTagNumbering(*this, Tag);
David Majnemeraa824612013-09-17 23:57:10 +00008951 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8952 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8953 }
Eli Friedman5e867c82013-07-10 00:30:46 +00008954 }
David Blaikie66cff722012-11-14 01:52:05 +00008955
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008956 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith406c38e2011-02-23 00:37:57 +00008957}
8958
8959/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8960/// group, performing any necessary semantic checking.
8961Sema::DeclGroupPtrTy
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008962Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith406c38e2011-02-23 00:37:57 +00008963 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00008964 // C++0x [dcl.spec.auto]p7:
8965 // If the type deduced for the template parameter U is not the same in each
8966 // deduction, the program is ill-formed.
8967 // FIXME: When initializer-list support is added, a distinction is needed
8968 // between the deduced type U and the deduced type which 'auto' stands for.
8969 // auto a = 0, b = { 1, 2, 3 };
8970 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008971 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00008972 QualType Deduced;
8973 CanQualType DeducedCanon;
8974 VarDecl *DeducedDecl = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008975 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith34b41d92011-02-20 03:19:35 +00008976 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8977 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00008978 // Don't reissue diagnostics when instantiating a template.
8979 if (AT && D->isInvalidDecl())
8980 break;
Richard Smithdc7a4f52013-04-30 13:56:41 +00008981 QualType U = AT ? AT->getDeducedType() : QualType();
8982 if (!U.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008983 CanQualType UCanon = Context.getCanonicalType(U);
8984 if (Deduced.isNull()) {
8985 Deduced = U;
8986 DeducedCanon = UCanon;
8987 DeducedDecl = D;
8988 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00008989 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
8990 diag::err_auto_different_deductions)
Richard Smithffd015e2013-05-04 04:19:27 +00008991 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith34b41d92011-02-20 03:19:35 +00008992 << Deduced << DeducedDecl->getDeclName()
8993 << U << D->getDeclName()
8994 << DeducedDecl->getInit()->getSourceRange()
8995 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00008996 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008997 break;
8998 }
8999 }
9000 }
9001 }
9002 }
9003
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009004 ActOnDocumentableDecls(Group);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009005
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009006 return DeclGroupPtrTy::make(
9007 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00009008}
Steve Naroffe1223f72007-08-28 03:03:08 +00009009
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009010void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009011 ActOnDocumentableDecls(D);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009012}
9013
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009014void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009015 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009016 if (Group.empty() || !Group[0])
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009017 return;
9018
9019 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9020 Group[0]->getLocation())
9021 == DiagnosticsEngine::Ignored)
9022 return;
9023
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009024 if (Group.size() >= 2) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009025 // This is a decl group. Normally it will contain only declarations
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009026 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009027 // additional declaration references:
9028 // 'typedef struct S {} S;'
9029 // 'typedef struct S *S;'
9030 // 'struct S *pS;'
9031 // FinalizeDeclaratorGroup adds these as separate declarations.
9032 Decl *MaybeTagDecl = Group[0];
9033 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009034 Group = Group.slice(1);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009035 }
9036 }
9037
9038 // See if there are any new comments that are not attached to a decl.
9039 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9040 if (!Comments.empty() &&
9041 !Comments.back()->isAttached()) {
9042 // There is at least one comment that not attached to a decl.
9043 // Maybe it should be attached to one of these decls?
9044 //
9045 // Note that this way we pick up not only comments that precede the
9046 // declaration, but also comments that *follow* the declaration -- thanks to
9047 // the lookahead in the lexer: we've consumed the semicolon and looked
9048 // ahead through comments.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009049 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko19523542012-09-29 11:40:46 +00009050 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009051 }
9052}
Chris Lattner682bf922009-03-29 16:50:03 +00009053
Chris Lattner04421082008-04-08 04:40:51 +00009054/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9055/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00009056Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00009057 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00009058
Chris Lattner04421082008-04-08 04:40:51 +00009059 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Valifad9e132013-09-26 19:54:12 +00009060
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009061 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00009062 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009063 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00009064 StorageClass = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00009065 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009066 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9067 StorageClass = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009068 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00009069 Diag(DS.getStorageClassSpecLoc(),
9070 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00009071 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00009072 }
Eli Friedman63054b32009-04-19 20:27:55 +00009073
Richard Smithec642442013-04-12 22:46:28 +00009074 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9075 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9076 << DeclSpec::getSpecifierName(TSCS);
9077 if (DS.isConstexprSpecified())
9078 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smithaf1fc7a2011-08-15 21:04:07 +00009079 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00009080
Richard Smithec642442013-04-12 22:46:28 +00009081 DiagnoseFunctionSpecifiers(DS);
Eli Friedman85a53192009-04-07 19:37:57 +00009082
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00009083 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00009084 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009085
David Blaikie4e4d0842012-03-11 07:00:24 +00009086 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009087 // Check that there are no default arguments inside the type of this
9088 // parameter.
9089 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009090
9091 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9092 if (D.getCXXScopeSpec().isSet()) {
9093 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9094 << D.getCXXScopeSpec().getRange();
9095 D.getCXXScopeSpec().clear();
9096 }
Douglas Gregor402abb52009-05-28 23:31:59 +00009097 }
9098
Sean Hunt7533a5b2010-11-03 01:07:06 +00009099 // Ensure we have a valid name
9100 IdentifierInfo *II = 0;
9101 if (D.hasName()) {
9102 II = D.getIdentifier();
9103 if (!II) {
9104 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9105 << GetNameForDeclarator(D).getName().getAsString();
9106 D.setInvalidType(true);
9107 }
9108 }
9109
Chris Lattnerd84aac12010-02-22 00:40:25 +00009110 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00009111 if (II) {
John McCall10f28732010-03-18 06:42:38 +00009112 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9113 ForRedeclaration);
9114 LookupName(R, S);
9115 if (R.isSingleResult()) {
9116 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00009117 if (PrevDecl->isTemplateParameter()) {
9118 // Maybe we will complain about the shadowed template parameter.
9119 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9120 // Just pretend that we didn't see the previous declaration.
9121 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00009122 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00009123 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00009124 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00009125
Chris Lattnercf79b012009-01-21 02:38:50 +00009126 // Recover by removing the name
9127 II = 0;
9128 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009129 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00009130 }
Chris Lattner04421082008-04-08 04:40:51 +00009131 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009132 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00009133
John McCall7a9813c2010-01-22 00:28:27 +00009134 // Temporarily put parameter variables in the translation unit, not
9135 // the enclosing context. This prevents them from accidentally
9136 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009137 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00009138 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009139 D.getIdentifierLoc(), II,
9140 parmDeclType, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009141 StorageClass);
Mike Stump1eb44332009-09-09 15:08:12 +00009142
Chris Lattnereaaebc72009-04-25 08:06:05 +00009143 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00009144 New->setInvalidDecl();
9145
9146 assert(S->isFunctionPrototypeScope());
9147 assert(S->getFunctionPrototypeDepth() >= 1);
9148 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9149 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009150
Douglas Gregor44b43212008-12-11 16:49:14 +00009151 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00009152 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009153 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00009154 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00009155
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009156 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00009157
Douglas Gregore3895852011-09-12 18:37:38 +00009158 if (D.getDeclSpec().isModulePrivateSpecified())
9159 Diag(New->getLocation(), diag::err_module_private_local)
9160 << 1 << New->getDeclName()
9161 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9162 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9163
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009164 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00009165 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9166 }
John McCalld226f652010-08-21 09:40:31 +00009167 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00009168}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00009169
John McCall82dc0092010-06-04 11:21:44 +00009170/// \brief Synthesizes a variable for a parameter arising from a
9171/// typedef.
9172ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9173 SourceLocation Loc,
9174 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009175 /* FIXME: setting StartLoc == Loc.
9176 Would it be worth to modify callers so as to provide proper source
9177 location for the unnamed parameters, embedding the parameter's type? */
9178 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00009179 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009180 SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00009181 Param->setImplicit();
9182 return Param;
9183}
9184
John McCallfbce0e12010-08-24 09:05:15 +00009185void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9186 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00009187 // Don't diagnose unused-parameter errors in template instantiations; we
9188 // will already have done so in the template itself.
9189 if (!ActiveTemplateInstantiations.empty())
9190 return;
9191
9192 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00009193 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00009194 !(*Param)->hasAttr<UnusedAttr>()) {
9195 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9196 << (*Param)->getDeclName();
9197 }
9198 }
9199}
9200
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009201void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9202 ParmVarDecl * const *ParamEnd,
9203 QualType ReturnTy,
9204 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009205 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009206 return;
9207
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009208 // Warn if the return value is pass-by-value and larger than the specified
9209 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00009210 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009211 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009212 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009213 Diag(D->getLocation(), diag::warn_return_value_size)
9214 << D->getDeclName() << Size;
9215 }
9216
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009217 // Warn if any parameter is pass-by-value and larger than the specified
9218 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009219 for (; Param != ParamEnd; ++Param) {
9220 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00009221 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009222 continue;
9223 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009224 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009225 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9226 << (*Param)->getDeclName() << Size;
9227 }
9228}
9229
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009230ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9231 SourceLocation NameLoc, IdentifierInfo *Name,
9232 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009233 VarDecl::StorageClass StorageClass) {
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009234 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00009235 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009236 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009237 T->isObjCLifetimeType()) {
9238
9239 Qualifiers::ObjCLifetime lifetime;
9240
9241 // Special cases for arrays:
9242 // - if it's const, use __unsafe_unretained
9243 // - otherwise, it's an error
9244 if (T->isArrayType()) {
9245 if (!T.isConstQualified()) {
9246 DelayedDiagnostics.add(
9247 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanian175fb102011-10-03 22:11:57 +00009248 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009249 }
9250 lifetime = Qualifiers::OCL_ExplicitNone;
9251 } else {
9252 lifetime = T->getObjCARCImplicitLifetime();
9253 }
9254 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCallf85e1932011-06-15 23:02:42 +00009255 }
9256
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009257 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00009258 Context.getAdjustedParameterType(T),
9259 TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009260 StorageClass, 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009261
9262 // Parameters can not be abstract class types.
9263 // For record types, this is done by the AbstractClassUsageDiagnoser once
9264 // the class has been completely parsed.
9265 if (!CurContext->isRecord() &&
9266 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9267 AbstractParamType))
9268 New->setInvalidDecl();
9269
9270 // Parameter declarators cannot be interface types. All ObjC objects are
9271 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00009272 if (T->isObjCObjectType()) {
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009273 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009274 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009275 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009276 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009277 T = Context.getObjCObjectPointerType(T);
9278 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009279 }
9280
9281 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9282 // duration shall not be qualified by an address-space qualifier."
9283 // Since all parameters have automatic store duration, they can not have
9284 // an address space.
9285 if (T.getAddressSpace() != 0) {
9286 Diag(NameLoc, diag::err_arg_with_address_space);
9287 New->setInvalidDecl();
9288 }
9289
9290 return New;
9291}
9292
Douglas Gregora3a83512009-04-01 23:51:29 +00009293void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9294 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009295 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00009296
Reid Spencer5f016e22007-07-11 17:01:13 +00009297 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9298 // for a K&R function.
9299 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00009300 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9301 --i;
Chris Lattner04421082008-04-08 04:40:51 +00009302 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009303 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009304 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009305 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009306 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00009307 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00009308 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00009309 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00009310
Reid Spencer5f016e22007-07-11 17:01:13 +00009311 // Implicitly declare the argument as type 'int' for lack of a better
9312 // type.
John McCall0b7e6782011-03-24 11:26:52 +00009313 AttributeFactory attrs;
9314 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00009315 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00009316 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00009317 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00009318 PrevSpec, DiagID);
Abramo Bagnara16467f22012-10-04 21:38:29 +00009319 // Use the identifier location for the type source range.
9320 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9321 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattner04421082008-04-08 04:40:51 +00009322 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9323 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00009324 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00009325 }
9326 }
Mike Stump1eb44332009-09-09 15:08:12 +00009327 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00009328}
9329
Richard Smith87162c22012-04-17 22:30:01 +00009330Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00009331 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009332 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00009333 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00009334
Douglas Gregor45fa5602011-11-07 20:56:01 +00009335 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009336 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner682bf922009-03-29 16:50:03 +00009337 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00009338}
9339
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009340static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9341 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009342 // Don't warn about invalid declarations.
9343 if (FD->isInvalidDecl())
9344 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009345
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009346 // Or declarations that aren't global.
9347 if (!FD->isGlobal())
9348 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009349
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009350 // Don't warn about C++ member functions.
9351 if (isa<CXXMethodDecl>(FD))
9352 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009353
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009354 // Don't warn about 'main'.
9355 if (FD->isMain())
9356 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009357
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009358 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00009359 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009360 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009361
9362 // Don't warn about function templates.
9363 if (FD->getDescribedFunctionTemplate())
9364 return false;
9365
9366 // Don't warn about function template specializations.
9367 if (FD->isFunctionTemplateSpecialization())
9368 return false;
9369
Tanya Lattnera95b4f72012-07-26 00:08:28 +00009370 // Don't warn for OpenCL kernels.
9371 if (FD->hasAttr<OpenCLKernelAttr>())
9372 return false;
Richard Smitha41c97a2013-09-20 01:15:31 +00009373
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009374 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00009375 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9376 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009377 // Ignore any declarations that occur in function or method
9378 // scope, because they aren't visible from the header.
Richard Smitha41c97a2013-09-20 01:15:31 +00009379 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009380 continue;
Richard Smitha41c97a2013-09-20 01:15:31 +00009381
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009382 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009383 if (FD->getNumParams() == 0)
9384 PossibleZeroParamPrototype = Prev;
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009385 break;
9386 }
Richard Smitha41c97a2013-09-20 01:15:31 +00009387
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009388 return MissingPrototype;
9389}
9390
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009391void
9392Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9393 const FunctionDecl *EffectiveDefinition) {
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009394 // Don't complain if we're in GNU89 mode and the previous definition
9395 // was an extern inline function.
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009396 const FunctionDecl *Definition = EffectiveDefinition;
9397 if (!Definition)
9398 if (!FD->isDefined(Definition))
9399 return;
9400
9401 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009402 return;
9403
9404 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9405 Definition->getStorageClass() == SC_Extern)
9406 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00009407 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009408 else
9409 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9410
9411 Diag(Definition->getLocation(), diag::note_previous_definition);
9412 FD->setInvalidDecl();
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009413}
Faisal Valibef582b2013-10-23 16:10:50 +00009414static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9415 Sema &S) {
9416 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9417 S.PushLambdaScope();
9418 LambdaScopeInfo *LSI = S.getCurLambda();
9419 LSI->CallOperator = CallOperator;
9420 LSI->Lambda = LambdaClass;
9421 LSI->ReturnType = CallOperator->getResultType();
9422 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9423
9424 if (LCD == LCD_None)
9425 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9426 else if (LCD == LCD_ByCopy)
9427 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9428 else if (LCD == LCD_ByRef)
9429 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9430 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9431
9432 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9433 LSI->Mutable = !CallOperator->isConst();
9434
9435 // FIXME: Add the captures to the LSI.
9436}
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009437
John McCalld226f652010-08-21 09:40:31 +00009438Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00009439 // Clear the last template instantiation error context.
9440 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9441
Douglas Gregor52591bf2009-06-24 00:54:41 +00009442 if (!D)
9443 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00009444 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00009445
John McCalld226f652010-08-21 09:40:31 +00009446 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00009447 FD = FunTmpl->getTemplatedDecl();
9448 else
John McCalld226f652010-08-21 09:40:31 +00009449 FD = cast<FunctionDecl>(D);
Faisal Valifad9e132013-09-26 19:54:12 +00009450 // If we are instantiating a generic lambda call operator, push
9451 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valibef582b2013-10-23 16:10:50 +00009452 // that's already been calculated (ActOnLambdaExpr) to prime the current
9453 // LambdaScopeInfo.
9454 // When the template operator is being specialized, the LambdaScopeInfo,
9455 // has to be properly restored so that tryCaptureVariable doesn't try
9456 // and capture any new variables. In addition when calculating potential
9457 // captures during transformation of nested lambdas, it is necessary to
9458 // have the LSI properly restored.
Faisal Vali998c5182013-09-29 20:15:45 +00009459 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Valifad9e132013-09-26 19:54:12 +00009460 assert(ActiveTemplateInstantiations.size() &&
9461 "There should be an active template instantiation on the stack "
9462 "when instantiating a generic lambda!");
Faisal Valibef582b2013-10-23 16:10:50 +00009463 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Valifad9e132013-09-26 19:54:12 +00009464 }
9465 else
9466 // Enter a new function scope
9467 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00009468
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009469 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009470 if (!FD->isLateTemplateParsed())
9471 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009472
Douglas Gregorcda9c672009-02-16 17:45:42 +00009473 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009474 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindolaad24ad42013-06-13 18:34:17 +00009475 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9476 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00009477 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00009478 FD->setInvalidDecl();
9479 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00009480 }
9481
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009482 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00009483 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9484 QualType ResultType = FD->getResultType();
9485 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00009486 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00009487 RequireCompleteType(FD->getLocation(), ResultType,
9488 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009489 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009490
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009491 // GNU warning -Wmissing-prototypes:
9492 // Warn if a global function is defined without a previous
9493 // prototype declaration. This warning is issued even if the
9494 // definition itself provides a prototype. The aim is to detect
9495 // global functions that fail to be declared in header files.
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009496 const FunctionDecl *PossibleZeroParamPrototype = 0;
9497 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009498 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithac83a3c2013-06-25 20:34:17 +00009499
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009500 if (PossibleZeroParamPrototype) {
Richard Smithac83a3c2013-06-25 20:34:17 +00009501 // We found a declaration that is not a prototype,
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009502 // but that could be a zero-parameter prototype
Richard Smithac83a3c2013-06-25 20:34:17 +00009503 if (TypeSourceInfo *TI =
9504 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9505 TypeLoc TL = TI->getTypeLoc();
9506 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9507 Diag(PossibleZeroParamPrototype->getLocation(),
9508 diag::note_declaration_not_a_prototype)
9509 << PossibleZeroParamPrototype
9510 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9511 }
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009512 }
9513 }
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009514
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009515 if (FnBodyScope)
9516 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009517
Chris Lattner04421082008-04-08 04:40:51 +00009518 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00009519 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9520 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00009521
9522 // Introduce our parameters into the function scope
9523 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9524 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00009525 Param->setOwningFunction(FD);
9526
Chris Lattner04421082008-04-08 04:40:51 +00009527 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009528 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009529 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00009530
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009531 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00009532 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009533 }
Chris Lattner04421082008-04-08 04:40:51 +00009534
James Molloy16f1f712012-02-29 10:24:19 +00009535 // If we had any tags defined in the function prototype,
9536 // introduce them into the function scope.
9537 if (FnBodyScope) {
Robert Wilhelm834c0582013-08-09 18:02:13 +00009538 for (ArrayRef<NamedDecl *>::iterator
9539 I = FD->getDeclsInPrototypeScope().begin(),
9540 E = FD->getDeclsInPrototypeScope().end();
9541 I != E; ++I) {
James Molloy16f1f712012-02-29 10:24:19 +00009542 NamedDecl *D = *I;
9543
9544 // Some of these decls (like enums) may have been pinned to the translation unit
9545 // for lack of a real context earlier. If so, remove from the translation unit
9546 // and reattach to the current context.
9547 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9548 // Is the decl actually in the context?
9549 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9550 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9551 if (*DI == D) {
9552 Context.getTranslationUnitDecl()->removeDecl(D);
9553 break;
9554 }
9555 }
9556 // Either way, reassign the lexical decl context to our FunctionDecl.
9557 D->setLexicalDeclContext(CurContext);
9558 }
9559
9560 // If the decl has a non-null name, make accessible in the current scope.
9561 if (!D->getName().empty())
9562 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9563
9564 // Similarly, dive into enums and fish their constants out, making them
9565 // accessible in this scope.
9566 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9567 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9568 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie581deb32012-06-06 20:45:41 +00009569 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy16f1f712012-02-29 10:24:19 +00009570 }
9571 }
9572 }
9573
Richard Smith87162c22012-04-17 22:30:01 +00009574 // Ensure that the function's exception specification is instantiated.
9575 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9576 ResolveExceptionSpec(D->getLocation(), FPT);
9577
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009578 // Checking attributes of current function definition
9579 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00009580 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9581 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9582 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00009583 // Microsoft accepts dllimport for functions defined within class scope.
9584 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00009585 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009586 Diag(FD->getLocation(),
9587 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9588 << "dllimport";
9589 FD->setInvalidDecl();
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009590 return D;
Ted Kremenek12911a82010-02-21 05:12:53 +00009591 }
9592
9593 // Visual C++ appears to not think this is an issue, so only issue
9594 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009595 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009596 // If a symbol previously declared dllimport is later defined, the
9597 // attribute is ignored in subsequent references, and a warning is
9598 // emitted.
9599 Diag(FD->getLocation(),
9600 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00009601 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009602 }
9603 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +00009604 // We want to attach documentation to original Decl (which might be
9605 // a function template).
9606 ActOnDocumentableDecl(D);
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009607 return D;
Reid Spencer5f016e22007-07-11 17:01:13 +00009608}
9609
Douglas Gregor5077c382010-05-15 06:01:05 +00009610/// \brief Given the set of return statements within a function body,
9611/// compute the variables that are subject to the named return value
9612/// optimization.
9613///
9614/// Each of the variables that is subject to the named return value
9615/// optimization will be marked as NRVO variables in the AST, and any
9616/// return statement that has a marked NRVO variable as its NRVO candidate can
9617/// use the named return value optimization.
9618///
9619/// This function applies a very simplistic algorithm for NRVO: if every return
9620/// statement in the function has the same NRVO candidate, that candidate is
9621/// the NRVO variable.
9622///
9623/// FIXME: Employ a smarter algorithm that accounts for multiple return
9624/// statements and the lifetimes of the NRVO candidates. We should be able to
9625/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009626void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00009627 ReturnStmt **Returns = Scope->Returns.data();
9628
Douglas Gregor5077c382010-05-15 06:01:05 +00009629 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00009630 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00009631 if (!Returns[I]->getNRVOCandidate())
9632 return;
9633
9634 if (!NRVOCandidate)
9635 NRVOCandidate = Returns[I]->getNRVOCandidate();
9636 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9637 return;
9638 }
9639
9640 if (NRVOCandidate)
9641 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9642}
9643
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009644bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smithd1bac8d2012-11-27 21:31:01 +00009645 if (!Consumer.shouldSkipFunctionBody(D))
9646 return false;
9647
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009648 if (isa<ObjCMethodDecl>(D))
9649 return true;
9650
9651 FunctionDecl *FD = 0;
9652 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9653 FD = FTD->getTemplatedDecl();
9654 else
9655 FD = cast<FunctionDecl>(D);
9656
9657 // We cannot skip the body of a function (or function template) which is
9658 // constexpr, since we may need to evaluate its body in order to parse the
9659 // rest of the file.
Richard Smith25d8c852013-05-10 04:31:10 +00009660 // We cannot skip the body of a function with an undeduced return type,
9661 // because any callers of that function need to know the type.
9662 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009663}
9664
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009665Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009666 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009667 FD->setHasSkippedBody();
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009668 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009669 MD->setHasSkippedBody();
9670 return ActOnFinishFunctionBody(Decl, 0);
9671}
9672
John McCallf312b1e2010-08-26 23:41:50 +00009673Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009674 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009675}
9676
John McCall9ae2f072010-08-23 23:25:46 +00009677Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9678 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00009679 FunctionDecl *FD = 0;
9680 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9681 if (FunTmpl)
9682 FD = FunTmpl->getTemplatedDecl();
9683 else
9684 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9685
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009686 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009687 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009688
Douglas Gregord83d0402009-08-22 00:34:47 +00009689 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00009690 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00009691
Richard Smith25d8c852013-05-10 04:31:10 +00009692 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9693 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9694 // If the function has a deduced result type but contains no 'return'
9695 // statements, the result type as written must be exactly 'auto', and
9696 // the deduced result type is 'void'.
9697 if (!FD->getResultType()->getAs<AutoType>()) {
9698 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9699 << FD->getResultType();
9700 FD->setInvalidDecl();
9701 } else {
9702 // Substitute 'void' for the 'auto' in the type.
9703 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9704 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9705 Context.adjustDeducedFunctionResultType(
9706 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith60e141e2013-05-04 07:00:32 +00009707 }
9708 }
9709
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009710 // The only way to be included in UndefinedButUsed is if there is an
9711 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewycky995e26b2013-01-31 03:23:57 +00009712 // is the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00009713 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00009714 if (!FD->isExternallyVisible())
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009715 UndefinedButUsed.erase(FD);
9716 else if (FD->isInlined() &&
9717 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9718 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9719 UndefinedButUsed.erase(FD);
9720 }
Nick Lewycky995e26b2013-01-31 03:23:57 +00009721
John McCall75d8ba32012-02-14 19:50:52 +00009722 // If the function implicitly returns zero (like 'main') or is naked,
9723 // don't complain about missing return statements.
9724 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009725 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00009726
Francois Pichet6a247472011-05-11 02:14:46 +00009727 // MSVC permits the use of pure specifier (=0) on function definition,
9728 // defined at class scope, warn about this non standard construct.
Reid Kleckner5dbed662013-10-08 22:45:29 +00009729 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet6a247472011-05-11 02:14:46 +00009730 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9731
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009732 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009733 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009734 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9735 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009736
9737 // If this is a constructor, we need a vtable.
9738 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9739 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00009740
Jordan Rose7dd900e2012-07-02 21:19:23 +00009741 // Try to apply the named return value optimization. We have to check
9742 // if we can do this here because lambdas keep return statements around
9743 // to deduce an implicit return type.
9744 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9745 !FD->isDependentContext())
9746 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009747 }
9748
Douglas Gregor76e3da52012-02-08 20:17:14 +00009749 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9750 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00009751 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00009752 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00009753 MD->setBody(Body);
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009754 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009755 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009756 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9757 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00009758
9759 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009760 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009761 }
Jordan Rose535a5d02012-10-19 16:05:26 +00009762 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanian9f559832012-09-10 16:51:09 +00009763 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9764 << MD->getSelector().getAsString();
Jordan Rose535a5d02012-10-19 16:05:26 +00009765 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00009766 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00009767 } else {
John McCalld226f652010-08-21 09:40:31 +00009768 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00009769 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009770
Jordan Rose535a5d02012-10-19 16:05:26 +00009771 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman95aac152012-08-01 21:02:59 +00009772 "This should only be set for ObjC methods, which should have been "
9773 "handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00009774
Reid Spencer5f016e22007-07-11 17:01:13 +00009775 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009776 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009777 // C++ constructors that have function-try-blocks can't have return
9778 // statements in the handlers of that block. (C++ [except.handle]p14)
9779 // Verify this.
9780 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9781 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9782
Richard Smith37bee672011-08-12 18:44:32 +00009783 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00009784 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00009785 !dcl->isInvalidDecl() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009786 !hasAnyUnrecoverableErrorsInThisFunction() &&
9787 !PP.isCodeCompletionEnabled())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009788 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00009789
John McCall15442822010-08-04 01:04:25 +00009790 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9791 if (!Destructor->getParent()->isDependentType())
9792 CheckDestructor(Destructor);
9793
John McCallef027fe2010-03-16 21:39:52 +00009794 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9795 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00009796 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009797
9798 // If any errors have occurred, clear out any temporaries that may have
9799 // been leftover. This ensures that these temporaries won't be picked up for
9800 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00009801 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00009802 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00009803 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00009804 }
9805 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9806 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009807 // Since the body is valid, issue any analysis-based warnings that are
9808 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009809 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009810 }
9811
Richard Smith86c3ae42012-02-13 03:54:03 +00009812 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9813 (!CheckConstexprFunctionDecl(FD) ||
9814 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00009815 FD->setInvalidDecl();
9816
John McCall80ee6e82011-11-10 05:35:25 +00009817 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00009818 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00009819 assert(MaybeODRUseExprs.empty() &&
9820 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009821 }
9822
John McCall90f97892010-03-25 22:08:03 +00009823 if (!IsInstantiation)
9824 PopDeclContext();
9825
Eli Friedmanec9ea722012-01-05 03:35:19 +00009826 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregord5b57282009-11-15 07:07:58 +00009827 // If any errors have occurred, clear out any temporaries that may have
9828 // been leftover. This ensures that these temporaries won't be picked up for
9829 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00009830 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00009831 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00009832 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00009833
John McCalld226f652010-08-21 09:40:31 +00009834 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00009835}
9836
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009837
9838/// When we finish delayed parsing of an attribute, we must attach it to the
9839/// relevant Decl.
9840void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9841 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00009842 // Always attach attributes to the underlying decl.
9843 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9844 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00009845 ProcessDeclAttributeList(S, D, Attrs.getList());
9846
9847 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9848 if (Method->isStatic())
9849 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009850}
9851
9852
Reid Spencer5f016e22007-07-11 17:01:13 +00009853/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9854/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00009855NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00009856 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00009857 // Before we produce a declaration for an implicitly defined
9858 // function, see whether there was a locally-scoped declaration of
9859 // this name as a function or variable. If so, use that
9860 // (non-visible) declaration, and complain about it.
Richard Smith662f41b2013-06-18 20:15:12 +00009861 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9862 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9863 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9864 return ExternCPrev;
Douglas Gregor63935192009-03-02 00:19:53 +00009865 }
9866
Chris Lattner37d10842008-05-05 21:18:06 +00009867 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009868 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009869 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00009870 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00009871 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009872 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00009873 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009874 diag_id = diag::warn_implicit_function_decl;
9875 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00009876
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009877 // Because typo correction is expensive, only do it if the implicit
9878 // function declaration is going to be treated as an error.
9879 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9880 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00009881 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009882 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smith2d670972013-08-17 00:46:16 +00009883 LookupOrdinaryName, S, 0, Validator)))
9884 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9885 /*ErrorRecovery*/false);
Hans Wennborg122de3e2011-12-06 09:46:12 +00009886 }
9887
Reid Spencer5f016e22007-07-11 17:01:13 +00009888 // Set a Declarator for the implicit definition: int foo();
9889 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00009890 AttributeFactory attrFactory;
9891 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00009892 unsigned DiagID;
9893 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00009894 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00009895 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009896 SourceLocation NoLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009897 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009898 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9899 /*IsAmbiguous=*/false,
9900 /*RParenLoc=*/NoLoc,
9901 /*ArgInfo=*/0,
9902 /*NumArgs=*/0,
9903 /*EllipsisLoc=*/NoLoc,
9904 /*RParenLoc=*/NoLoc,
9905 /*TypeQuals=*/0,
9906 /*RefQualifierIsLvalueRef=*/true,
9907 /*RefQualifierLoc=*/NoLoc,
9908 /*ConstQualifierLoc=*/NoLoc,
9909 /*VolatileQualifierLoc=*/NoLoc,
9910 /*MutableLoc=*/NoLoc,
9911 EST_None,
9912 /*ESpecLoc=*/NoLoc,
9913 /*Exceptions=*/0,
9914 /*ExceptionRanges=*/0,
9915 /*NumExceptions=*/0,
9916 /*NoexceptExpr=*/0,
9917 Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00009918 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00009919 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00009920 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00009921
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009922 // Insert this function into translation-unit scope.
9923
9924 DeclContext *PrevDC = CurContext;
9925 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009926
Jordan Rose41f3f3a2013-03-05 01:27:54 +00009927 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00009928 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009929
9930 CurContext = PrevDC;
9931
Douglas Gregor3c385e52009-02-14 18:57:46 +00009932 AddKnownFunctionAttributes(FD);
9933
Steve Naroffe2ef8152008-04-04 14:32:09 +00009934 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009935}
9936
Douglas Gregor3c385e52009-02-14 18:57:46 +00009937/// \brief Adds any function attributes that we know a priori based on
9938/// the declaration of this function.
9939///
9940/// These attributes can apply both to implicitly-declared builtins
9941/// (like __builtin___printf_chk) or to library-declared functions
9942/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009943///
9944/// We need to check for duplicate attributes both here and where user-written
9945/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +00009946void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9947 if (FD->isInvalidDecl())
9948 return;
9949
9950 // If this is a built-in function, map its builtin attributes to
9951 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009952 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00009953 // Handle printf-formatting attributes.
9954 unsigned FormatIdx;
9955 bool HasVAListArg;
9956 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009957 if (!FD->getAttr<FormatAttr>()) {
9958 const char *fmt = "printf";
9959 unsigned int NumParams = FD->getNumParams();
9960 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
9961 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
9962 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +00009963 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00009964 &Context.Idents.get(fmt),
9965 FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00009966 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009967 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00009968 }
Ted Kremenekbee05c12010-07-16 02:11:15 +00009969 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
9970 HasVAListArg)) {
9971 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009972 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00009973 &Context.Idents.get("scanf"),
9974 FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +00009975 HasVAListArg ? 0 : FormatIdx+2));
9976 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009977
9978 // Mark const if we don't care about errno and that is the only
9979 // thing preventing the function from being const. This allows
9980 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +00009981 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009982 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009983 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009984 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009985 }
Mike Stump0feecbb2009-07-27 19:14:18 +00009986
Rafael Espindola67004152011-10-12 19:51:18 +00009987 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
9988 !FD->getAttr<ReturnsTwiceAttr>())
9989 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009990 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009991 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009992 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009993 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +00009994 }
9995
9996 IdentifierInfo *Name = FD->getIdentifier();
9997 if (!Name)
9998 return;
David Blaikie4e4d0842012-03-11 07:00:24 +00009999 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +000010000 FD->getDeclContext()->isTranslationUnit()) ||
10001 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +000010002 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +000010003 LinkageSpecDecl::lang_c)) {
10004 // Okay: this could be a libc/libm/Objective-C function we know
10005 // about.
10006 } else
10007 return;
10008
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010009 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +000010010 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +000010011 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010012 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010013 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010014 &Context.Idents.get("printf"), 2,
Eli Friedmand7dad722009-06-10 04:01:38 +000010015 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +000010016 }
Jordan Rose8a64f882012-08-08 21:17:31 +000010017
10018 if (Name->isStr("__CFStringMakeConstantString")) {
10019 // We already have a __builtin___CFStringMakeConstantString,
10020 // but builds that use -fno-constant-cfstrings don't go through that.
10021 if (!FD->getAttr<FormatArgAttr>())
10022 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10023 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010024}
Reid Spencer5f016e22007-07-11 17:01:13 +000010025
John McCallba6a9bd2009-10-24 08:00:42 +000010026TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000010027 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010028 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +000010029 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +000010030
John McCalla93c9342009-12-07 02:54:59 +000010031 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +000010032 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +000010033 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +000010034 }
10035
Reid Spencer5f016e22007-07-11 17:01:13 +000010036 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +000010037 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010038 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +000010039 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +000010040 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +000010041 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +000010042
John McCallcde5a402011-02-01 08:20:08 +000010043 // Bail out immediately if we have an invalid declaration.
10044 if (D.isInvalidType()) {
10045 NewTD->setInvalidDecl();
10046 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +000010047 }
10048
Douglas Gregore3895852011-09-12 18:37:38 +000010049 if (D.getDeclSpec().isModulePrivateSpecified()) {
10050 if (CurContext->isFunctionOrMethod())
10051 Diag(NewTD->getLocation(), diag::err_module_private_local)
10052 << 2 << NewTD->getDeclName()
10053 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10054 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10055 else
10056 NewTD->setModulePrivate();
10057 }
Douglas Gregor8d267c52011-09-09 02:06:17 +000010058
John McCallcde5a402011-02-01 08:20:08 +000010059 // C++ [dcl.typedef]p8:
10060 // If the typedef declaration defines an unnamed class (or
10061 // enum), the first typedef-name declared by the declaration
10062 // to be that class type (or enum type) is used to denote the
10063 // class type (or enum type) for linkage purposes only.
10064 // We need to check whether the type was declared in the declaration.
10065 switch (D.getDeclSpec().getTypeSpecType()) {
10066 case TST_enum:
10067 case TST_struct:
Joao Matos6666ed42012-08-31 18:45:21 +000010068 case TST_interface:
John McCallcde5a402011-02-01 08:20:08 +000010069 case TST_union:
10070 case TST_class: {
10071 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10072
10073 // Do nothing if the tag is not anonymous or already has an
10074 // associated typedef (from an earlier typedef in this decl group).
10075 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +000010076 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +000010077
10078 // A well-formed anonymous tag must always be a TUK_Definition.
10079 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10080
10081 // The type must match the tag exactly; no qualifiers allowed.
10082 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10083 break;
10084
10085 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +000010086 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +000010087 break;
10088 }
10089
10090 default:
10091 break;
10092 }
10093
Steve Naroff5912a352007-08-28 20:14:24 +000010094 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +000010095}
10096
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010097
Richard Smithf1c66b42012-03-14 23:13:10 +000010098/// \brief Check that this is a valid underlying type for an enum declaration.
10099bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10100 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10101 QualType T = TI->getType();
10102
Eli Friedman2fcff832012-12-18 02:37:32 +000010103 if (T->isDependentType())
Richard Smithf1c66b42012-03-14 23:13:10 +000010104 return false;
10105
Eli Friedman2fcff832012-12-18 02:37:32 +000010106 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10107 if (BT->isInteger())
10108 return false;
10109
Richard Smithf1c66b42012-03-14 23:13:10 +000010110 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10111 return true;
10112}
10113
10114/// Check whether this is a valid redeclaration of a previous enumeration.
10115/// \return true if the redeclaration was invalid.
10116bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10117 QualType EnumUnderlyingTy,
10118 const EnumDecl *Prev) {
10119 bool IsFixed = !EnumUnderlyingTy.isNull();
10120
10121 if (IsScoped != Prev->isScoped()) {
10122 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10123 << Prev->isScoped();
10124 Diag(Prev->getLocation(), diag::note_previous_use);
10125 return true;
10126 }
10127
10128 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +000010129 if (!EnumUnderlyingTy->isDependentType() &&
10130 !Prev->getIntegerType()->isDependentType() &&
10131 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +000010132 Prev->getIntegerType())) {
10133 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10134 << EnumUnderlyingTy << Prev->getIntegerType();
10135 Diag(Prev->getLocation(), diag::note_previous_use);
10136 return true;
10137 }
10138 } else if (IsFixed != Prev->isFixed()) {
10139 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10140 << Prev->isFixed();
10141 Diag(Prev->getLocation(), diag::note_previous_use);
10142 return true;
10143 }
10144
10145 return false;
10146}
10147
Joao Matos6666ed42012-08-31 18:45:21 +000010148/// \brief Get diagnostic %select index for tag kind for
10149/// redeclaration diagnostic message.
10150/// WARNING: Indexes apply to particular diagnostics only!
10151///
10152/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +000010153static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +000010154 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +000010155 case TTK_Struct: return 0;
10156 case TTK_Interface: return 1;
10157 case TTK_Class: return 2;
10158 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +000010159 }
Joao Matos6666ed42012-08-31 18:45:21 +000010160}
10161
10162/// \brief Determine if tag kind is a class-key compatible with
10163/// class for redeclaration (class, struct, or __interface).
10164///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000010165/// \returns true iff the tag kind is compatible.
Joao Matos6666ed42012-08-31 18:45:21 +000010166static bool isClassCompatTagKind(TagTypeKind Tag)
10167{
10168 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10169}
10170
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010171/// \brief Determine whether a tag with a given kind is acceptable
10172/// as a redeclaration of the given tag declaration.
10173///
10174/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +000010175bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +000010176 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010177 SourceLocation NewTagLoc,
10178 const IdentifierInfo &Name) {
10179 // C++ [dcl.type.elab]p3:
10180 // The class-key or enum keyword present in the
10181 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010182 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010183 // refers. This rule also applies to the form of
10184 // elaborated-type-specifier that declares a class-name or
10185 // friend class since it can be construed as referring to the
10186 // definition of the class. Thus, in any
10187 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010188 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010189 // used to refer to a union (clause 9), and either the class or
10190 // struct class-key shall be used to refer to a class (clause 9)
10191 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010192 TagTypeKind OldTag = Previous->getTagKind();
Joao Matos6666ed42012-08-31 18:45:21 +000010193 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieubbf34c02011-06-10 03:11:26 +000010194 if (OldTag == NewTag)
10195 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010196
Joao Matos6666ed42012-08-31 18:45:21 +000010197 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010198 // Warn about the struct/class tag mismatch.
10199 bool isTemplate = false;
10200 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10201 isTemplate = Record->getDescribedClassTemplate();
10202
Richard Trieubbf34c02011-06-10 03:11:26 +000010203 if (!ActiveTemplateInstantiations.empty()) {
10204 // In a template instantiation, do not offer fix-its for tag mismatches
10205 // since they usually mess up the template instead of fixing the problem.
10206 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010207 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10208 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010209 return true;
10210 }
10211
10212 if (isDefinition) {
10213 // On definitions, check previous tags and issue a fix-it for each
10214 // one that doesn't match the current tag.
10215 if (Previous->getDefinition()) {
10216 // Don't suggest fix-its for redefinitions.
10217 return true;
10218 }
10219
10220 bool previousMismatch = false;
10221 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10222 E(Previous->redecls_end()); I != E; ++I) {
10223 if (I->getTagKind() != NewTag) {
10224 if (!previousMismatch) {
10225 previousMismatch = true;
10226 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010227 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10228 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieubbf34c02011-06-10 03:11:26 +000010229 }
10230 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010231 << getRedeclDiagFromTagKind(NewTag)
Richard Trieubbf34c02011-06-10 03:11:26 +000010232 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matos6666ed42012-08-31 18:45:21 +000010233 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieubbf34c02011-06-10 03:11:26 +000010234 }
10235 }
10236 return true;
10237 }
10238
10239 // Check for a previous definition. If current tag and definition
10240 // are same type, do nothing. If no definition, but disagree with
10241 // with previous tag type, give a warning, but no fix-it.
10242 const TagDecl *Redecl = Previous->getDefinition() ?
10243 Previous->getDefinition() : Previous;
10244 if (Redecl->getTagKind() == NewTag) {
10245 return true;
10246 }
10247
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010248 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010249 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10250 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010251 Diag(Redecl->getLocation(), diag::note_previous_use);
10252
10253 // If there is a previous defintion, suggest a fix-it.
10254 if (Previous->getDefinition()) {
10255 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010256 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieubbf34c02011-06-10 03:11:26 +000010257 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matos6666ed42012-08-31 18:45:21 +000010258 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieubbf34c02011-06-10 03:11:26 +000010259 }
10260
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010261 return true;
10262 }
10263 return false;
10264}
10265
Steve Naroff08d92e42007-09-15 18:49:24 +000010266/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +000010267/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +000010268/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +000010269/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +000010270Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +000010271 SourceLocation KWLoc, CXXScopeSpec &SS,
10272 IdentifierInfo *Name, SourceLocation NameLoc,
10273 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010274 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +000010275 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010276 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010277 SourceLocation ScopedEnumKWLoc,
10278 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010279 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010280 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +000010281 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +000010282 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000010283 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +000010284 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010285
Douglas Gregor402abb52009-05-28 23:31:59 +000010286 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010287 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +000010288 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +000010289
Douglas Gregor1fef4e62009-10-07 22:35:40 +000010290 // FIXME: Check explicit specializations more carefully.
10291 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010292 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +000010293
10294 // We only need to do this matching if we have template parameters
10295 // or a scope specifier, which also conveniently avoids this work
10296 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010297 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +000010298 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000010299 if (TemplateParameterList *TemplateParams =
10300 MatchTemplateParametersToScopeSpecifier(
10301 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10302 isExplicitSpecialization, Invalid)) {
Richard Smith725fe0e2013-04-01 21:43:41 +000010303 if (Kind == TTK_Enum) {
10304 Diag(KWLoc, diag::err_enum_template);
10305 return 0;
10306 }
10307
Douglas Gregord85bea22009-09-26 06:47:28 +000010308 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010309 // This is a declaration or definition of a class template (which may
10310 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010311
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010312 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +000010313 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010314
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010315 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +000010316 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010317 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010318 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010319 ModulePrivateLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010320 TemplateParameterLists.size()-1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010321 TemplateParameterLists.data());
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010322 return Result.get();
10323 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +000010324 // The "template<>" header is extraneous.
10325 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010326 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +000010327 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010328 }
Mike Stump1eb44332009-09-09 15:08:12 +000010329 }
10330 }
10331
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010332 // Figure out the underlying type if this a enum declaration. We need to do
10333 // this early, because it's needed to detect if this is an incompatible
10334 // redeclaration.
10335 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10336
10337 if (Kind == TTK_Enum) {
10338 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10339 // No underlying type explicitly specified, or we failed to parse the
10340 // type, default to int.
10341 EnumUnderlying = Context.IntTy.getTypePtr();
10342 else if (UnderlyingType.get()) {
10343 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10344 // integral type; any cv-qualification is ignored.
10345 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +000010346 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010347 EnumUnderlying = TI;
10348
Richard Smithf1c66b42012-03-14 23:13:10 +000010349 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010350 // Recover by falling back to int.
10351 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010352
Richard Smithf1c66b42012-03-14 23:13:10 +000010353 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010354 UPPC_FixedUnderlyingType))
10355 EnumUnderlying = Context.IntTy.getTypePtr();
10356
David Blaikie4e4d0842012-03-11 07:00:24 +000010357 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +000010358 // Microsoft enums are always of int type.
10359 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010360 }
10361
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010362 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010363 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010364 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010365
Chandler Carruth7bf36002010-03-01 21:17:36 +000010366 RedeclarationKind Redecl = ForRedeclaration;
10367 if (TUK == TUK_Friend || TUK == TUK_Reference)
10368 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +000010369
10370 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregord9433522013-06-27 20:42:30 +000010371 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010372 if (Name && SS.isNotEmpty()) {
10373 // We have a nested-name tag ('struct foo::bar').
10374
10375 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010376 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010377 Name = 0;
10378 goto CreateNewDecl;
10379 }
10380
John McCallc4e70192009-09-11 04:59:25 +000010381 // If this is a friend or a reference to a class in a dependent
10382 // context, don't try to make a decl for it.
10383 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10384 DC = computeDeclContext(SS, false);
10385 if (!DC) {
10386 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010387 return 0;
John McCallc4e70192009-09-11 04:59:25 +000010388 }
John McCall77bb1aa2010-05-01 00:40:08 +000010389 } else {
10390 DC = computeDeclContext(SS, true);
10391 if (!DC) {
10392 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10393 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +000010394 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +000010395 }
John McCallc4e70192009-09-11 04:59:25 +000010396 }
10397
John McCall77bb1aa2010-05-01 00:40:08 +000010398 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +000010399 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +000010400
Douglas Gregor1931b442009-02-03 00:34:39 +000010401 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010402 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +000010403 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +000010404
John McCall68263142009-11-18 22:49:29 +000010405 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010406 return 0;
John McCall6e247262009-10-10 05:48:19 +000010407
John McCall68263142009-11-18 22:49:29 +000010408 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010409 // Name lookup did not find anything. However, if the
10410 // nested-name-specifier refers to the current instantiation,
10411 // and that current instantiation has any dependent base
10412 // classes, we might find something at instantiation time: treat
10413 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +000010414 // But this only makes any sense for reference-like lookups.
10415 if (Previous.wasNotFoundInCurrentInstantiation() &&
10416 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010417 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010418 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010419 }
10420
10421 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +000010422 Diag(NameLoc, diag::err_not_tag_in_scope)
10423 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010424 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +000010425 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010426 goto CreateNewDecl;
10427 }
Chris Lattnercf79b012009-01-21 02:38:50 +000010428 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010429 // If this is a named struct, check to see if there was a previous forward
10430 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +000010431 // FIXME: We're looking into outer scopes here, even when we
10432 // shouldn't be. Doing so can result in ambiguities that we
10433 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +000010434 LookupName(Previous, S);
10435
John McCallc96cd7a2013-03-20 01:53:00 +000010436 // When declaring or defining a tag, ignore ambiguities introduced
10437 // by types using'ed into this scope.
Douglas Gregor93b6bce2011-05-09 21:46:33 +000010438 if (Previous.isAmbiguous() &&
10439 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +000010440 LookupResult::Filter F = Previous.makeFilter();
10441 while (F.hasNext()) {
10442 NamedDecl *ND = F.next();
10443 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10444 F.erase();
10445 }
10446 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +000010447 }
John McCallc96cd7a2013-03-20 01:53:00 +000010448
10449 // C++11 [namespace.memdef]p3:
10450 // If the name in a friend declaration is neither qualified nor
10451 // a template-id and the declaration is a function or an
10452 // elaborated-type-specifier, the lookup to determine whether
10453 // the entity has been previously declared shall not consider
10454 // any scopes outside the innermost enclosing namespace.
10455 //
10456 // Does it matter that this should be by scope instead of by
10457 // semantic context?
10458 if (!Previous.empty() && TUK == TUK_Friend) {
10459 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10460 LookupResult::Filter F = Previous.makeFilter();
10461 while (F.hasNext()) {
10462 NamedDecl *ND = F.next();
10463 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregord9433522013-06-27 20:42:30 +000010464 if (DC->isFileContext() &&
10465 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCallc96cd7a2013-03-20 01:53:00 +000010466 F.erase();
Douglas Gregord9433522013-06-27 20:42:30 +000010467 FriendSawTagOutsideEnclosingNamespace = true;
10468 }
John McCallc96cd7a2013-03-20 01:53:00 +000010469 }
10470 F.done();
10471 }
Douglas Gregor61c6c442011-05-04 00:25:33 +000010472
John McCall68263142009-11-18 22:49:29 +000010473 // Note: there used to be some attempt at recovery here.
10474 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010475 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +000010476
David Blaikie4e4d0842012-03-11 07:00:24 +000010477 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +000010478 // FIXME: This makes sure that we ignore the contexts associated
10479 // with C structs, unions, and enums when looking for a matching
10480 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +000010481 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010482 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10483 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +000010484 }
Douglas Gregor069ea642010-09-16 23:58:57 +000010485 } else if (S->isFunctionPrototypeScope()) {
10486 // If this is an enum declaration in function prototype scope, set its
10487 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +000010488 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +000010489 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010490 }
10491
John McCall68263142009-11-18 22:49:29 +000010492 if (Previous.isSingleResult() &&
10493 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010494 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +000010495 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +000010496 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +000010497 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +000010498 }
10499
David Blaikie4e4d0842012-03-11 07:00:24 +000010500 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010501 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010502 // This is a declaration of or a reference to "std::bad_alloc".
10503 isStdBadAlloc = true;
10504
John McCall68263142009-11-18 22:49:29 +000010505 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010506 // std::bad_alloc has been implicitly declared (but made invisible to
10507 // name lookup). Fill in this implicit declaration as the previous
10508 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010509 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010510 }
10511 }
John McCall68263142009-11-18 22:49:29 +000010512
John McCall9c86b512010-03-25 21:28:06 +000010513 // If we didn't find a previous declaration, and this is a reference
10514 // (or friend reference), move to the correct scope. In C++, we
10515 // also need to do a redeclaration lookup there, just in case
10516 // there's a shadow friend decl.
10517 if (Name && Previous.empty() &&
10518 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10519 if (Invalid) goto CreateNewDecl;
10520 assert(SS.isEmpty());
10521
10522 if (TUK == TUK_Reference) {
10523 // C++ [basic.scope.pdecl]p5:
10524 // -- for an elaborated-type-specifier of the form
10525 //
10526 // class-key identifier
10527 //
10528 // if the elaborated-type-specifier is used in the
10529 // decl-specifier-seq or parameter-declaration-clause of a
10530 // function defined in namespace scope, the identifier is
10531 // declared as a class-name in the namespace that contains
10532 // the declaration; otherwise, except as a friend
10533 // declaration, the identifier is declared in the smallest
10534 // non-class, non-function-prototype scope that contains the
10535 // declaration.
10536 //
10537 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10538 // C structs and unions.
10539 //
10540 // It is an error in C++ to declare (rather than define) an enum
10541 // type, including via an elaborated type specifier. We'll
10542 // diagnose that later; for now, declare the enum in the same
10543 // scope as we would have picked for any other tag type.
10544 //
10545 // GNU C also supports this behavior as part of its incomplete
10546 // enum types extension, while GNU C++ does not.
10547 //
10548 // Find the context where we'll be declaring the tag.
10549 // FIXME: We would like to maintain the current DeclContext as the
10550 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +000010551 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +000010552 SearchDC = SearchDC->getParent();
10553
10554 // Find the scope where we'll be declaring the tag.
10555 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010556 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +000010557 S->isFunctionPrototypeScope()) ||
10558 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +000010559 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCall9c86b512010-03-25 21:28:06 +000010560 S = S->getParent();
10561 } else {
10562 assert(TUK == TUK_Friend);
10563 // C++ [namespace.memdef]p3:
10564 // If a friend declaration in a non-local class first declares a
10565 // class or function, the friend class or function is a member of
10566 // the innermost enclosing namespace.
10567 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +000010568 }
10569
John McCall0d6b1642010-04-23 18:46:30 +000010570 // In C++, we need to do a redeclaration lookup to properly
10571 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +000010572 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +000010573 Previous.setRedeclarationKind(ForRedeclaration);
10574 LookupQualifiedName(Previous, SearchDC);
10575 }
10576 }
10577
John McCall68263142009-11-18 22:49:29 +000010578 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +000010579 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +000010580
10581 // It's okay to have a tag decl in the same scope as a typedef
10582 // which hides a tag decl in the same scope. Finding this
10583 // insanity with a redeclaration lookup can only actually happen
10584 // in C++.
10585 //
10586 // This is also okay for elaborated-type-specifiers, which is
10587 // technically forbidden by the current standard but which is
10588 // okay according to the likely resolution of an open issue;
10589 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +000010590 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +000010591 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +000010592 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10593 TagDecl *Tag = TT->getDecl();
10594 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010595 Tag->getDeclContext()->getRedeclContext()
10596 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +000010597 PrevDecl = Tag;
10598 Previous.clear();
10599 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +000010600 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +000010601 }
10602 }
10603 }
10604 }
10605
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010606 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010607 // If this is a use of a previous tag, or if the tag is already declared
10608 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010609 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +000010610 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +000010611 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010612 // Make sure that this wasn't declared as an enum and now used as a
10613 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +000010614 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10615 TUK == TUK_Definition, KWLoc,
10616 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +000010617 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010618 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10619 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +000010620 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +000010621 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +000010622 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +000010623 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10624 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +000010625 else
10626 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +000010627 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +000010628
Mike Stump1eb44332009-09-09 15:08:12 +000010629 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +000010630 Kind = PrevTagDecl->getTagKind();
10631 else {
10632 // Recover by making this an anonymous redefinition.
10633 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010634 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +000010635 Invalid = true;
10636 }
10637 }
10638
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010639 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10640 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10641
Richard Smithbdad7a22012-01-10 01:33:14 +000010642 // If this is an elaborated-type-specifier for a scoped enumeration,
10643 // the 'class' keyword is not necessary and not permitted.
10644 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10645 if (ScopedEnum)
10646 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10647 << PrevEnum->isScoped()
10648 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10649 return PrevTagDecl;
10650 }
10651
Richard Smithf1c66b42012-03-14 23:13:10 +000010652 QualType EnumUnderlyingTy;
10653 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10654 EnumUnderlyingTy = TI->getType();
10655 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10656 EnumUnderlyingTy = QualType(T, 0);
10657
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010658 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +000010659 // returning the previous declaration, unless this is a definition,
10660 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +000010661 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10662 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +000010663 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010664 }
10665
David Majnemer2ec2b842013-06-11 03:51:23 +000010666 // C++11 [class.mem]p1:
David Majnemer0f9b8552013-06-11 06:19:45 +000010667 // A member shall not be declared twice in the member-specification,
David Majnemer2ec2b842013-06-11 03:51:23 +000010668 // except that a nested class or member class template can be declared
10669 // and then later defined.
10670 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10671 S->isDeclScope(PrevDecl)) {
10672 Diag(NameLoc, diag::ext_member_redeclared);
10673 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10674 }
10675
Douglas Gregora3a83512009-04-01 23:51:29 +000010676 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010677 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +000010678
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010679 // FIXME: In the future, return a variant or some other clue
10680 // for the consumer of this Decl to know it doesn't own it.
10681 // For our current ASTs this shouldn't be a problem, but will
10682 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +000010683 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010684 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +000010685 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010686
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010687 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +000010688 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +000010689 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010690 // If we're defining a specialization and the previous definition
10691 // is from an implicit instantiation, don't emit an error
10692 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +000010693 bool IsExplicitSpecializationAfterInstantiation = false;
10694 if (isExplicitSpecialization) {
10695 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10696 IsExplicitSpecializationAfterInstantiation =
10697 RD->getTemplateSpecializationKind() !=
10698 TSK_ExplicitSpecialization;
10699 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10700 IsExplicitSpecializationAfterInstantiation =
10701 ED->getTemplateSpecializationKind() !=
10702 TSK_ExplicitSpecialization;
10703 }
10704
10705 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +000010706 // A redeclaration in function prototype scope in C isn't
10707 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +000010708 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +000010709 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10710 else
10711 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010712 Diag(Def->getLocation(), diag::note_previous_definition);
10713 // If this is a redefinition, recover by making this
10714 // struct be anonymous, which will make any later
10715 // references get the previous definition.
10716 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010717 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010718 Invalid = true;
10719 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010720 } else {
10721 // If the type is currently being defined, complain
10722 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +000010723 const TagType *Tag
10724 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010725 if (Tag->isBeingDefined()) {
10726 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +000010727 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010728 diag::note_previous_definition);
10729 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010730 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010731 Invalid = true;
10732 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010733 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010734
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010735 // Okay, this is definition of a previously declared or referenced
10736 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010737 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010738 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010739 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +000010740 // have a definition. Just create a new decl.
10741
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010742 } else {
10743 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +000010744 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010745 // new decl/type. We set PrevDecl to NULL so that the entities
10746 // have distinct types.
John McCall68263142009-11-18 22:49:29 +000010747 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010748 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010749 // If we get here, we're going to create a new Decl. If PrevDecl
10750 // is non-NULL, it's a definition of the tag declared by
10751 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +000010752
10753
10754 // Otherwise, PrevDecl is not a tag, but was found with tag
10755 // lookup. This is only actually possible in C++, where a few
10756 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010757 } else {
John McCall0d6b1642010-04-23 18:46:30 +000010758 // Use a better diagnostic if an elaborated-type-specifier
10759 // found the wrong kind of type on the first
10760 // (non-redeclaration) lookup.
10761 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10762 !Previous.isForRedeclaration()) {
10763 unsigned Kind = 0;
10764 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010765 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10766 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010767 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10768 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10769 Invalid = true;
10770
10771 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +000010772 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10773 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +000010774 // do nothing
10775
10776 // Diagnose implicit declarations introduced by elaborated types.
10777 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10778 unsigned Kind = 0;
10779 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010780 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10781 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010782 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10783 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10784 Invalid = true;
10785
10786 // Otherwise it's a declaration. Call out a particularly common
10787 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +000010788 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10789 unsigned Kind = 0;
10790 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +000010791 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +000010792 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +000010793 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10794 Invalid = true;
10795
10796 // Otherwise, diagnose.
10797 } else {
10798 // The tag name clashes with something else in the target scope,
10799 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +000010800 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010801 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010802 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010803 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010804 }
John McCall0d6b1642010-04-23 18:46:30 +000010805
10806 // The existing declaration isn't relevant to us; we're in a
10807 // new scope, so clear out the previous declaration.
10808 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010809 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010810 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000010811
Chris Lattnercc98eac2008-12-17 07:13:27 +000010812CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +000010813
John McCall68263142009-11-18 22:49:29 +000010814 TagDecl *PrevDecl = 0;
10815 if (Previous.isSingleResult())
10816 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10817
Reid Spencer5f016e22007-07-11 17:01:13 +000010818 // If there is an identifier, use the location of the identifier as the
10819 // location of the decl, otherwise use the location of the struct/union
10820 // keyword.
10821 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000010822
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010823 // Otherwise, create a new declaration. If there is a previous
10824 // declaration of the same entity, the two will be linked via
10825 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +000010826 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +000010827
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010828 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010829 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010830 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10831 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010832 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010833 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010834 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +000010835 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010836 if (TUK != TUK_Definition && !Invalid) {
10837 TagDecl *Def;
Douglas Gregorabde2c72013-03-25 22:22:35 +000010838 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10839 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010840 // C++0x: 7.2p2: opaque-enum-declaration.
10841 // Conflicts are diagnosed above. Do nothing.
10842 }
10843 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010844 Diag(Loc, diag::ext_forward_ref_enum_def)
10845 << New;
10846 Diag(Def->getLocation(), diag::note_previous_definition);
10847 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010848 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010849 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010850 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010851 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010852 DiagID = diag::err_forward_ref_enum;
10853 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010854
10855 // If this is a forward-declared reference to an enumeration, make a
10856 // note of it; we won't actually be introducing the declaration into
10857 // the declaration context.
10858 if (TUK == TUK_Reference)
10859 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010860 }
Douglas Gregor80711a22009-03-06 18:34:03 +000010861 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010862
10863 if (EnumUnderlying) {
10864 EnumDecl *ED = cast<EnumDecl>(New);
10865 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10866 ED->setIntegerTypeSourceInfo(TI);
10867 else
10868 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10869 ED->setPromotionType(ED->getIntegerType());
10870 }
10871
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000010872 } else {
10873 // struct/union/class
10874
Reid Spencer5f016e22007-07-11 17:01:13 +000010875 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10876 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +000010877 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +000010878 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010879 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010880 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010881
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010882 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010883 StdBadAlloc = cast<CXXRecordDecl>(New);
10884 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010885 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010886 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000010887 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010888
John McCallb6217662010-03-15 10:12:16 +000010889 // Maybe add qualifier info.
10890 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010891 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +000010892 // If this is either a declaration or a definition, check the
10893 // nested-name-specifier against the current context. We don't do this
10894 // for explicit specializations, because they have similar checking
10895 // (with more specific diagnostics) in the call to
10896 // CheckMemberSpecialization, below.
10897 if (!isExplicitSpecialization &&
10898 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10899 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10900 Invalid = true;
10901
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000010902 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010903 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +000010904 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010905 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010906 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +000010907 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010908 }
10909 else
10910 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +000010911 }
10912
Daniel Dunbar9f21f892010-05-27 01:53:40 +000010913 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10914 // Add alignment attributes if necessary; these attributes are checked when
10915 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010916 //
10917 // It is important for implementing the correct semantics that this
10918 // happen here (in act on tag decl). The #pragma pack stack is
10919 // maintained as a result of parser callbacks which can occur at
10920 // many points during the parsing of a struct declaration (because
10921 // the #pragma tokens are effectively skipped over during the
10922 // parsing of the struct).
Eli Friedman2016c8c2012-08-08 21:08:34 +000010923 if (TUK == TUK_Definition) {
10924 AddAlignmentAttributesForRecord(RD);
10925 AddMsStructLayoutForRecord(RD);
10926 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010927 }
10928
Douglas Gregor2ccd89c2011-12-20 18:11:52 +000010929 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +000010930 if (isExplicitSpecialization)
10931 Diag(New->getLocation(), diag::err_module_private_specialization)
10932 << 2
10933 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +000010934 // __module_private__ does not apply to local classes. However, we only
10935 // diagnose this as an error when the declaration specifiers are
10936 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +000010937 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +000010938 New->setModulePrivate();
10939 }
10940
Douglas Gregorf6b11852009-10-08 15:14:33 +000010941 // If this is a specialization of a member class (of a class template),
10942 // check the specialization.
John McCall68263142009-11-18 22:49:29 +000010943 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +000010944 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +000010945
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010946 if (Invalid)
10947 New->setInvalidDecl();
10948
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010949 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010950 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010951
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010952 // If we're declaring or defining a tag in function prototype scope
10953 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +000010954 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +000010955 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
10956
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010957 // Set the lexical context. If the tag has a C++ scope specifier, the
10958 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +000010959 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010960
John McCall02cace72009-08-28 07:59:38 +000010961 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +000010962 // In Microsoft mode, a friend declaration also acts as a forward
10963 // declaration so we always pass true to setObjectOfFriendDecl to make
10964 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +000010965 if (TUK == TUK_Friend)
Richard Smith22050f22013-07-17 23:53:16 +000010966 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
10967 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +000010968
Anders Carlsson0cf88302009-03-26 01:19:02 +000010969 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +000010970 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +000010971 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +000010972
John McCall0f434ec2009-07-31 02:45:11 +000010973 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010974 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +000010975
Reid Spencer5f016e22007-07-11 17:01:13 +000010976 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +000010977 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +000010978 // We might be replacing an existing declaration in the lookup tables;
10979 // if so, borrow its access specifier.
10980 if (PrevDecl)
10981 New->setAccess(PrevDecl->getAccess());
10982
Sebastian Redl7a126a42010-08-31 00:36:30 +000010983 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010984 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +000010985 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +000010986 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10987 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +000010988 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000010989 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010990 PushOnScopeChains(New, S, !IsForwardReference);
10991 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010992 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010993
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010994 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010995 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +000010996 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000010997
Douglas Gregorc29f77b2009-07-07 16:35:42 +000010998 // If this is the C FILE type, notify the AST context.
10999 if (IdentifierInfo *II = New->getIdentifier())
11000 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000011001 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011002 II->isStr("FILE"))
11003 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +000011004
James Molloy16f1f712012-02-29 10:24:19 +000011005 // If we were in function prototype scope (and not in C++ mode), add this
11006 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +000011007 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +000011008 InFunctionDeclarator && Name)
11009 DeclsInPrototypeScope.push_back(New);
11010
Rafael Espindola98ae8342012-05-10 02:50:16 +000011011 if (PrevDecl)
11012 mergeDeclAttributes(New, PrevDecl);
11013
Rafael Espindola71adc5b2012-07-17 15:14:47 +000011014 // If there's a #pragma GCC visibility in scope, set the visibility of this
11015 // record.
11016 AddPushedVisibilityAttribute(New);
11017
Douglas Gregor402abb52009-05-28 23:31:59 +000011018 OwnedDecl = true;
Richard Smith37ec8d52012-12-05 11:34:06 +000011019 // In C++, don't return an invalid declaration. We can't recover well from
11020 // the cases where we make the type anonymous.
11021 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Reid Spencer5f016e22007-07-11 17:01:13 +000011022}
11023
John McCalld226f652010-08-21 09:40:31 +000011024void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011025 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011026 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +000011027
Douglas Gregor72de6672009-01-08 20:45:30 +000011028 // Enter the tag context.
11029 PushDeclContext(S, Tag);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000011030
11031 ActOnDocumentableDecl(TagD);
Rafael Espindola5e065292012-07-12 04:47:34 +000011032
11033 // If there's a #pragma GCC visibility in scope, set the visibility of this
11034 // record.
11035 AddPushedVisibilityAttribute(Tag);
John McCallf9368152009-12-20 07:58:13 +000011036}
Douglas Gregor72de6672009-01-08 20:45:30 +000011037
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011038Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011039 assert(isa<ObjCContainerDecl>(IDecl) &&
11040 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11041 DeclContext *OCD = cast<DeclContext>(IDecl);
11042 assert(getContainingDC(OCD) == CurContext &&
11043 "The next DeclContext should be lexically contained in the current one.");
11044 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011045 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011046}
11047
John McCalld226f652010-08-21 09:40:31 +000011048void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011049 SourceLocation FinalLoc,
David Majnemer7121bdb2013-10-18 00:33:31 +000011050 bool IsFinalSpelledSealed,
John McCallf9368152009-12-20 07:58:13 +000011051 SourceLocation LBraceLoc) {
11052 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011053 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +000011054
John McCallf9368152009-12-20 07:58:13 +000011055 FieldCollector->StartClass();
11056
11057 if (!Record->getIdentifier())
11058 return;
11059
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011060 if (FinalLoc.isValid())
David Majnemer7121bdb2013-10-18 00:33:31 +000011061 Record->addAttr(new (Context)
11062 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11063
John McCallf9368152009-12-20 07:58:13 +000011064 // C++ [class]p2:
11065 // [...] The class-name is also inserted into the scope of the
11066 // class itself; this is known as the injected-class-name. For
11067 // purposes of access checking, the injected-class-name is treated
11068 // as if it were a public member name.
11069 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000011070 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11071 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +000011072 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +000011073 /*PrevDecl=*/0,
11074 /*DelayTypeCreation=*/true);
11075 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +000011076 InjectedClassName->setImplicit();
11077 InjectedClassName->setAccess(AS_public);
11078 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11079 InjectedClassName->setDescribedClassTemplate(Template);
11080 PushOnScopeChains(InjectedClassName, S);
11081 assert(InjectedClassName->isInjectedClassName() &&
11082 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +000011083}
11084
John McCalld226f652010-08-21 09:40:31 +000011085void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011086 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011087 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011088 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011089 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +000011090
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011091 // Make sure we "complete" the definition even it is invalid.
11092 if (Tag->isBeingDefined()) {
11093 assert(Tag->isInvalidDecl() && "We should already have completed it");
11094 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11095 RD->completeDefinition();
11096 }
11097
Douglas Gregor72de6672009-01-08 20:45:30 +000011098 if (isa<CXXRecordDecl>(Tag))
11099 FieldCollector->FinishClass();
11100
11101 // Exit this scope of this tag's definition.
11102 PopDeclContext();
Argyrios Kyrtzidis3d207e72013-01-29 18:00:54 +000011103
11104 if (getCurLexicalContext()->isObjCContainer() &&
11105 Tag->getDeclContext()->isFileContext())
11106 Tag->setTopLevelDeclInObjCContainer();
11107
Douglas Gregor72de6672009-01-08 20:45:30 +000011108 // Notify the consumer that we've defined a tag.
Serge Pavlov439b7012013-07-02 17:31:56 +000011109 if (!Tag->isInvalidDecl())
11110 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor72de6672009-01-08 20:45:30 +000011111}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +000011112
Fariborz Jahanian10af8792011-08-29 17:33:12 +000011113void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011114 // Exit this scope of this interface definition.
11115 PopDeclContext();
11116}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011117
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011118void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +000011119 assert(DC == CurContext && "Mismatch of container contexts");
11120 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011121 ActOnObjCContainerFinishDefinition();
11122}
11123
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011124void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11125 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011126 OriginalLexicalContext = 0;
11127}
11128
John McCalld226f652010-08-21 09:40:31 +000011129void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +000011130 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011131 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +000011132 Tag->setInvalidDecl();
11133
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011134 // Make sure we "complete" the definition even it is invalid.
11135 if (Tag->isBeingDefined()) {
11136 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11137 RD->completeDefinition();
11138 }
11139
John McCalla8cab012010-03-17 19:25:57 +000011140 // We're undoing ActOnTagStartDefinition here, not
11141 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11142 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +000011143
11144 PopDeclContext();
11145}
11146
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011147// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +000011148ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11149 IdentifierInfo *FieldName,
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011150 QualType FieldTy, bool IsMsStruct,
11151 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +000011152 // Default to true; that shouldn't confuse checks for emptiness
11153 if (ZeroWidth)
11154 *ZeroWidth = true;
11155
Chris Lattner24793662009-03-05 22:45:59 +000011156 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +000011157 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000011158 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +000011159 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +000011160 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +000011161 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011162 if (FieldName)
11163 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11164 << FieldName << FieldTy << BitWidth->getSourceRange();
11165 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11166 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +000011167 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11168 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +000011169 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011170
11171 // If the bit-width is type- or value-dependent, don't try to check
11172 // it now.
11173 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +000011174 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011175
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011176 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +000011177 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11178 if (ICE.isInvalid())
11179 return ICE;
11180 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011181
Eli Friedman1d954f62009-08-15 21:55:26 +000011182 if (Value != 0 && ZeroWidth)
11183 *ZeroWidth = false;
11184
Chris Lattnercd087072008-12-12 04:56:04 +000011185 // Zero-width bitfield is ok for anonymous field.
11186 if (Value == 0 && FieldName)
11187 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +000011188
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011189 if (Value.isSigned() && Value.isNegative()) {
11190 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +000011191 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011192 << FieldName << Value.toString(10);
11193 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11194 << Value.toString(10);
11195 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011196
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011197 if (!FieldTy->isDependentType()) {
11198 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011199 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011200 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlsson72468ec2010-04-16 15:16:32 +000011201 if (FieldName)
11202 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11203 << FieldName << (unsigned)Value.getZExtValue()
11204 << (unsigned)TypeSize;
11205
11206 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11207 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11208 }
11209
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011210 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +000011211 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11212 << FieldName << (unsigned)Value.getZExtValue()
11213 << (unsigned)TypeSize;
11214 else
11215 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11216 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011217 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011218 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011219
Richard Smith282e7e62012-02-04 09:53:13 +000011220 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011221}
11222
Richard Smith7a614d82011-06-11 17:19:42 +000011223/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +000011224/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +000011225Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011226 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +000011227 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +000011228 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smithca523302012-06-10 03:12:00 +000011229 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCalld226f652010-08-21 09:40:31 +000011230 return Res;
Chris Lattner24793662009-03-05 22:45:59 +000011231}
11232
11233/// HandleField - Analyze a field of a C struct or a C++ data member.
11234///
11235FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11236 SourceLocation DeclStart,
Richard Smithca523302012-06-10 03:12:00 +000011237 Declarator &D, Expr *BitWidth,
11238 InClassInitStyle InitStyle,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011239 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011240 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +000011241 SourceLocation Loc = DeclStart;
11242 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011243
John McCallbf1a0282010-06-04 23:28:52 +000011244 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11245 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +000011246 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011247 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +000011248
Douglas Gregore1862692010-12-15 23:18:36 +000011249 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11250 UPPC_DataMemberType)) {
11251 D.setInvalidType();
11252 T = Context.IntTy;
11253 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11254 }
11255 }
11256
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011257 // TR 18037 does not allow fields to be declared with address spaces.
11258 if (T.getQualifiers().hasAddressSpace()) {
11259 Diag(Loc, diag::err_field_with_address_space);
11260 D.setInvalidType();
11261 }
11262
Guy Benyeie6b9d802013-01-20 12:31:11 +000011263 // OpenCL 1.2 spec, s6.9 r:
11264 // The event type cannot be used to declare a structure or union field.
11265 if (LangOpts.OpenCL && T->isEventT()) {
11266 Diag(Loc, diag::err_event_t_struct_field);
11267 D.setInvalidType();
11268 }
11269
Richard Smithc7f81162013-03-18 22:52:47 +000011270 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +000011271
Richard Smithec642442013-04-12 22:46:28 +000011272 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11273 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11274 diag::err_invalid_thread)
11275 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011276
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011277 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +000011278 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011279 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11280 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +000011281 switch (Previous.getResultKind()) {
11282 case LookupResult::Found:
11283 case LookupResult::FoundUnresolvedValue:
11284 PrevDecl = Previous.getAsSingle<NamedDecl>();
11285 break;
11286
11287 case LookupResult::FoundOverloaded:
11288 PrevDecl = Previous.getRepresentativeDecl();
11289 break;
11290
11291 case LookupResult::NotFound:
11292 case LookupResult::NotFoundInCurrentInstantiation:
11293 case LookupResult::Ambiguous:
11294 break;
11295 }
11296 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +000011297
11298 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11299 // Maybe we will complain about the shadowed template parameter.
11300 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11301 // Just pretend that we didn't see the previous declaration.
11302 PrevDecl = 0;
11303 }
11304
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011305 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11306 PrevDecl = 0;
11307
Steve Naroffea218b82009-07-14 14:58:18 +000011308 bool Mutable
11309 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +000011310 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +000011311 FieldDecl *NewFD
Richard Smithca523302012-06-10 03:12:00 +000011312 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith7a614d82011-06-11 17:19:42 +000011313 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +000011314
11315 if (NewFD->isInvalidDecl())
11316 Record->setInvalidDecl();
11317
Douglas Gregor591dc842011-09-12 16:11:24 +000011318 if (D.getDeclSpec().isModulePrivateSpecified())
11319 NewFD->setModulePrivate();
11320
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011321 if (NewFD->isInvalidDecl() && PrevDecl) {
11322 // Don't introduce NewFD into scope; there's already something
11323 // with the same name in the same scope.
11324 } else if (II) {
11325 PushOnScopeChains(NewFD, S);
11326 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011327 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011328
11329 return NewFD;
11330}
11331
11332/// \brief Build a new FieldDecl and check its well-formedness.
11333///
11334/// This routine builds a new FieldDecl given the fields name, type,
11335/// record, etc. \p PrevDecl should refer to any previous declaration
11336/// with the same name and in the same scope as the field to be
11337/// created.
11338///
11339/// \returns a new FieldDecl.
11340///
Mike Stump1eb44332009-09-09 15:08:12 +000011341/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +000011342FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000011343 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011344 RecordDecl *Record, SourceLocation Loc,
Richard Smithca523302012-06-10 03:12:00 +000011345 bool Mutable, Expr *BitWidth,
11346 InClassInitStyle InitStyle,
Steve Naroffea218b82009-07-14 14:58:18 +000011347 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011348 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011349 Declarator *D) {
11350 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +000011351 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +000011352 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +000011353
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011354 // If we receive a broken type, recover by assuming 'int' and
11355 // marking this declaration as invalid.
11356 if (T.isNull()) {
11357 InvalidDecl = true;
11358 T = Context.IntTy;
11359 }
11360
Eli Friedman721e77d2009-12-07 00:22:08 +000011361 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011362 if (!EltTy->isDependentType()) {
11363 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11364 // Fields of incomplete type force their record to be invalid.
11365 Record->setInvalidDecl();
11366 InvalidDecl = true;
11367 } else {
11368 NamedDecl *Def;
11369 EltTy->isIncompleteType(&Def);
11370 if (Def && Def->isInvalidDecl()) {
11371 Record->setInvalidDecl();
11372 InvalidDecl = true;
11373 }
11374 }
John McCall2d7d2d92010-08-16 23:42:35 +000011375 }
Eli Friedman721e77d2009-12-07 00:22:08 +000011376
Joey Gouly617bb312013-01-17 17:35:00 +000011377 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11378 if (BitWidth && getLangOpts().OpenCL) {
11379 Diag(Loc, diag::err_opencl_bitfields);
11380 InvalidDecl = true;
11381 }
11382
Reid Spencer5f016e22007-07-11 17:01:13 +000011383 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11384 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +000011385 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011386 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +000011387 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011388
11389 TypeSourceInfo *FixedTInfo =
11390 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11391 SizeIsNegative,
11392 Oversized);
11393 if (FixedTInfo) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011394 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011395 TInfo = FixedTInfo;
11396 T = FixedTInfo->getType();
Eli Friedman1ca48132009-02-21 00:44:51 +000011397 } else {
11398 if (SizeIsNegative)
11399 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +000011400 else if (Oversized.getBoolValue())
11401 Diag(Loc, diag::err_array_too_large)
11402 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +000011403 else
11404 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +000011405 InvalidDecl = true;
11406 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011407 }
Mike Stump1eb44332009-09-09 15:08:12 +000011408
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011409 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +000011410 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11411 diag::err_abstract_type_in_decl,
11412 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011413 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +000011414
Eli Friedman1d954f62009-08-15 21:55:26 +000011415 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011416 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +000011417 if (!InvalidDecl && BitWidth) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011418 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11419 &ZeroWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011420 if (!BitWidth) {
11421 InvalidDecl = true;
11422 BitWidth = 0;
11423 ZeroWidth = false;
11424 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011425 }
Mike Stump1eb44332009-09-09 15:08:12 +000011426
John McCall4bde1e12010-06-04 08:34:12 +000011427 // Check that 'mutable' is consistent with the type of the declaration.
11428 if (!InvalidDecl && Mutable) {
11429 unsigned DiagID = 0;
11430 if (T->isReferenceType())
11431 DiagID = diag::err_mutable_reference;
11432 else if (T.isConstQualified())
11433 DiagID = diag::err_mutable_const;
11434
11435 if (DiagID) {
11436 SourceLocation ErrLoc = Loc;
11437 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11438 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11439 Diag(ErrLoc, DiagID);
11440 Mutable = false;
11441 InvalidDecl = true;
11442 }
11443 }
11444
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011445 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +000011446 BitWidth, Mutable, InitStyle);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011447 if (InvalidDecl)
11448 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +000011449
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011450 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11451 Diag(Loc, diag::err_duplicate_member) << II;
11452 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11453 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +000011454 }
11455
David Blaikie4e4d0842012-03-11 07:00:24 +000011456 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +000011457 if (Record->isUnion()) {
11458 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11459 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11460 if (RDecl->getDefinition()) {
11461 // C++ [class.union]p1: An object of a class with a non-trivial
11462 // constructor, a non-trivial copy constructor, a non-trivial
11463 // destructor, or a non-trivial copy assignment operator
11464 // cannot be a member of a union, nor can an array of such
11465 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +000011466 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +000011467 NewFD->setInvalidDecl();
11468 }
11469 }
11470
11471 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballman76eed422013-05-30 16:20:00 +000011472 // the program is ill-formed, except when compiling with MSVC extensions
11473 // enabled.
Anders Carlssondfdfc582010-11-07 19:13:55 +000011474 if (EltTy->isReferenceType()) {
Aaron Ballman76eed422013-05-30 16:20:00 +000011475 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11476 diag::ext_union_member_of_reference_type :
11477 diag::err_union_member_of_reference_type)
Anders Carlssondfdfc582010-11-07 19:13:55 +000011478 << NewFD->getDeclName() << EltTy;
Aaron Ballman76eed422013-05-30 16:20:00 +000011479 if (!getLangOpts().MicrosoftExt)
11480 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +000011481 }
11482 }
11483 }
11484
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011485 // FIXME: We need to pass in the attributes given an AST
11486 // representation, not a parser representation.
Richard Smithbe507b62013-02-01 08:12:08 +000011487 if (D) {
Douglas Gregor92eb7d82013-05-02 23:25:32 +000011488 // FIXME: The current scope is almost... but not entirely... correct here.
11489 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011490
Richard Smithbe507b62013-02-01 08:12:08 +000011491 if (NewFD->hasAttrs())
11492 CheckAlignasUnderalignment(NewFD);
11493 }
11494
John McCallf85e1932011-06-15 23:02:42 +000011495 // In auto-retain/release, infer strong retension for fields of
11496 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011497 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +000011498 NewFD->setInvalidDecl();
11499
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +000011500 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +000011501 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +000011502
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011503 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +000011504 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +000011505}
11506
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011507bool Sema::CheckNontrivialField(FieldDecl *FD) {
11508 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +000011509 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011510
Nick Lewyckydccd04d2013-06-25 23:22:23 +000011511 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11512 return false;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011513
11514 QualType EltTy = Context.getBaseElementType(FD->getType());
11515 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smithac713512012-12-08 02:53:02 +000011516 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011517 if (RDecl->getDefinition()) {
11518 // We check for copy constructors before constructors
11519 // because otherwise we'll never get complaints about
11520 // copy constructors.
11521
11522 CXXSpecialMember member = CXXInvalid;
Richard Smith426391c2012-11-16 00:53:38 +000011523 // We're required to check for any non-trivial constructors. Since the
11524 // implicit default constructor is suppressed if there are any
11525 // user-declared constructors, we just need to check that there is a
11526 // trivial default constructor and a trivial copy constructor. (We don't
11527 // worry about move constructors here, since this is a C++98 check.)
11528 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011529 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +000011530 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +000011531 member = CXXDefaultConstructor;
Richard Smith426391c2012-11-16 00:53:38 +000011532 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011533 member = CXXCopyAssignment;
Richard Smith426391c2012-11-16 00:53:38 +000011534 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011535 member = CXXDestructor;
11536
11537 if (member != CXXInvalid) {
Richard Smith80ad52f2013-01-02 11:42:31 +000011538 if (!getLangOpts().CPlusPlus11 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011539 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +000011540 // Objective-C++ ARC: it is an error to have a non-trivial field of
11541 // a union. However, system headers in Objective-C programs
11542 // occasionally have Objective-C lifetime objects within unions,
11543 // and rather than cause the program to fail, we make those
11544 // members unavailable.
11545 SourceLocation Loc = FD->getLocation();
11546 if (getSourceManager().isInSystemHeader(Loc)) {
11547 if (!FD->hasAttr<UnavailableAttr>())
11548 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011549 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011550 return false;
11551 }
11552 }
Richard Smithe7d7c392011-10-19 20:41:51 +000011553
Richard Smith80ad52f2013-01-02 11:42:31 +000011554 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithe7d7c392011-10-19 20:41:51 +000011555 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11556 diag::err_illegal_union_or_anon_struct_member)
11557 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smithac713512012-12-08 02:53:02 +000011558 DiagnoseNontrivial(RDecl, member);
Richard Smith80ad52f2013-01-02 11:42:31 +000011559 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011560 }
11561 }
11562 }
Richard Smithac713512012-12-08 02:53:02 +000011563
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011564 return false;
11565}
11566
Mike Stump1eb44332009-09-09 15:08:12 +000011567/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011568/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011569static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011570TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +000011571 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +000011572 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +000011573 case tok::objc_private: return ObjCIvarDecl::Private;
11574 case tok::objc_public: return ObjCIvarDecl::Public;
11575 case tok::objc_protected: return ObjCIvarDecl::Protected;
11576 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +000011577 }
11578}
11579
Mike Stump1eb44332009-09-09 15:08:12 +000011580/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +000011581/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +000011582Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +000011583 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011584 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +000011585 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +000011586
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011587 IdentifierInfo *II = D.getIdentifier();
11588 Expr *BitWidth = (Expr*)BitfieldWidth;
11589 SourceLocation Loc = DeclStart;
11590 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011591
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011592 // FIXME: Unnamed fields can be handled in various different ways, for
11593 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +000011594
John McCallbf1a0282010-06-04 23:28:52 +000011595 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11596 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000011597
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011598 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +000011599 // 6.7.2.1p3, 6.7.2.1p4
Warren Huntb2969b12013-10-11 20:19:00 +000011600 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011601 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +000011602 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011603 } else {
11604 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +000011605
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011606 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +000011607
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011608 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011609 if (T->isReferenceType()) {
11610 Diag(Loc, diag::err_ivar_reference_type);
11611 D.setInvalidType();
11612 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011613 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11614 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011615 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +000011616 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011617 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011618 }
Mike Stump1eb44332009-09-09 15:08:12 +000011619
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011620 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +000011621 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011622 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11623 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011624 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011625 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +000011626 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11627 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +000011628 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +000011629 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011630 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011631 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011632 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +000011633 EnclosingContext = IMPDecl->getClassInterface();
11634 assert(EnclosingContext && "Implementation has no class interface!");
11635 }
11636 else
11637 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011638 } else {
11639 if (ObjCCategoryDecl *CDecl =
11640 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011641 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011642 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +000011643 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011644 }
11645 }
Daniel Dunbara19331f2010-04-02 18:29:09 +000011646 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011647 }
Mike Stump1eb44332009-09-09 15:08:12 +000011648
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011649 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011650 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11651 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +000011652 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +000011653
Douglas Gregor72de6672009-01-08 20:45:30 +000011654 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000011655 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +000011656 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011657 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +000011658 && !isa<TagDecl>(PrevDecl)) {
11659 Diag(Loc, diag::err_duplicate_member) << II;
11660 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11661 NewID->setInvalidDecl();
11662 }
11663 }
11664
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011665 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011666 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +000011667
Chris Lattnereaaebc72009-04-25 08:06:05 +000011668 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011669 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011670
John McCallf85e1932011-06-15 23:02:42 +000011671 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011672 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +000011673 NewID->setInvalidDecl();
11674
Douglas Gregor591dc842011-09-12 16:11:24 +000011675 if (D.getDeclSpec().isModulePrivateSpecified())
11676 NewID->setModulePrivate();
11677
Douglas Gregor72de6672009-01-08 20:45:30 +000011678 if (II) {
11679 // FIXME: When interfaces are DeclContexts, we'll need to add
11680 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +000011681 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +000011682 IdResolver.AddDecl(NewID);
11683 }
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011684
John McCall260611a2012-06-20 06:18:46 +000011685 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011686 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniandc3eb6a2012-05-15 17:43:16 +000011687 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011688
John McCalld226f652010-08-21 09:40:31 +000011689 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011690}
11691
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011692/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosed4582b82013-04-03 01:39:23 +000011693/// class and class extensions. For every class \@interface and class
11694/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011695/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011696void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011697 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall260611a2012-06-20 06:18:46 +000011698 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011699 return;
11700
11701 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11702 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11703
Richard Smitha6b8b2c2011-10-10 18:28:20 +000011704 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011705 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011706 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011707 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011708 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011709 if (!CD->IsClassExtension())
11710 return;
11711 }
11712 // No need to add this to end of @implementation.
11713 else
11714 return;
11715 }
11716 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011717 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11718 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011719
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011720 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011721 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011722 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011723 Context.getTrivialTypeSourceInfo(Context.CharTy,
11724 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011725 ObjCIvarDecl::Private, BW,
11726 true);
11727 AllIvarDecls.push_back(Ivar);
11728}
11729
Robert Wilhelm834c0582013-08-09 18:02:13 +000011730void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11731 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11732 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +000011733 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +000011734
Eric Christopher6dba4a12012-07-19 22:22:51 +000011735 // If this is an Objective-C @implementation or category and we have
11736 // new fields here we should reset the layout of the interface since
11737 // it will now change.
11738 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11739 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11740 switch (DC->getKind()) {
11741 default: break;
11742 case Decl::ObjCCategory:
11743 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11744 break;
11745 case Decl::ObjCImplementation:
11746 Context.
11747 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11748 break;
11749 }
11750 }
11751
Eli Friedman11e70d72012-02-07 05:00:47 +000011752 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11753
11754 // Start counting up the number of named members; make sure to include
11755 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +000011756 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +000011757 if (Record) {
11758 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11759 e = Record->decls_end(); i != e; i++) {
11760 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11761 if (IFD->getDeclName())
11762 ++NumNamedMembers;
11763 }
11764 }
11765
11766 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011767 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011768
John McCallf85e1932011-06-15 23:02:42 +000011769 bool ARCErrReported = false;
Robert Wilhelm834c0582013-08-09 18:02:13 +000011770 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie77b6de02011-09-22 02:58:26 +000011771 i != end; ++i) {
11772 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +000011773
Reid Spencer5f016e22007-07-11 17:01:13 +000011774 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +000011775 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011776
Douglas Gregor72de6672009-01-08 20:45:30 +000011777 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011778 // Remember all fields written by the user.
11779 RecFields.push_back(FD);
11780 }
Mike Stump1eb44332009-09-09 15:08:12 +000011781
Chris Lattner24793662009-03-05 22:45:59 +000011782 // If the field is already invalid for some reason, don't emit more
11783 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +000011784 if (FD->isInvalidDecl()) {
11785 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +000011786 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +000011787 }
Mike Stump1eb44332009-09-09 15:08:12 +000011788
Douglas Gregore7450f52009-03-24 19:52:54 +000011789 // C99 6.7.2.1p2:
11790 // A structure or union shall not contain a member with
11791 // incomplete or function type (hence, a structure shall not
11792 // contain an instance of itself, but may contain a pointer to
11793 // an instance of itself), except that the last member of a
11794 // structure with more than one named member may have incomplete
11795 // array type; such a structure (and any union containing,
11796 // possibly recursively, a member that is such a structure)
11797 // shall not be a member of a structure or an element of an
11798 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +000011799 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011800 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011801 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011802 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011803 FD->setInvalidDecl();
11804 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011805 continue;
Francois Pichet09246182010-09-15 00:14:08 +000011806 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +000011807 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +000011808 ((getLangOpts().MicrosoftExt ||
11809 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +000011810 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011811 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011812 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +000011813 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +000011814 // as the sole element of a struct/class.
David Blaikie4e4d0842012-03-11 07:00:24 +000011815 if (getLangOpts().MicrosoftExt) {
Francois Pichet09246182010-09-15 00:14:08 +000011816 if (Record->isUnion())
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011817 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichet09246182010-09-15 00:14:08 +000011818 << FD->getDeclName();
David Blaikie77b6de02011-09-22 02:58:26 +000011819 else if (Fields.size() == 1)
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011820 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichet09246182010-09-15 00:14:08 +000011821 << FD->getDeclName() << Record->getTagKind();
David Blaikie4e4d0842012-03-11 07:00:24 +000011822 } else if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011823 if (Record->isUnion())
11824 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11825 << FD->getDeclName();
David Blaikie77b6de02011-09-22 02:58:26 +000011826 else if (Fields.size() == 1)
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011827 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
11828 << FD->getDeclName() << Record->getTagKind();
David Chisnall0961a012012-03-16 12:15:37 +000011829 } else if (!getLangOpts().C99) {
11830 if (Record->isUnion())
11831 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11832 << FD->getDeclName();
11833 else
11834 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11835 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011836 } else if (NumNamedMembers < 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011837 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011838 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011839 FD->setInvalidDecl();
11840 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011841 continue;
11842 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011843 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +000011844 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011845 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +000011846 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011847 FD->setInvalidDecl();
11848 EnclosingDecl->setInvalidDecl();
11849 continue;
11850 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011851 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +000011852 if (Record)
11853 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +000011854 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +000011855 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +000011856 diag::err_field_incomplete)) {
11857 // Incomplete type
11858 FD->setInvalidDecl();
11859 EnclosingDecl->setInvalidDecl();
11860 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +000011861 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011862 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11863 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000011864 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011865 Record->setHasFlexibleArrayMember(true);
11866 } else {
11867 // If this is a struct/class and this is not the last element, reject
11868 // it. Note that GCC supports variable sized arrays in the middle of
11869 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +000011870 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +000011871 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +000011872 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +000011873 else {
11874 // We support flexible arrays at the end of structs in
11875 // other structs as an extension.
11876 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11877 << FD->getDeclName();
11878 if (Record)
11879 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011880 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011881 }
11882 }
Fariborz Jahanian7f90b532012-08-16 22:38:41 +000011883 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11884 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11885 diag::err_abstract_type_in_decl,
11886 AbstractIvarType)) {
11887 // Ivars can not have abstract class types
11888 FD->setInvalidDecl();
11889 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000011890 if (Record && FDTTy->getDecl()->hasObjectMember())
11891 Record->setHasObjectMember(true);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011892 if (Record && FDTTy->getDecl()->hasVolatileMember())
11893 Record->setHasVolatileMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +000011894 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011895 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +000011896 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11897 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11898 QualType T = Context.getObjCObjectPointerType(FD->getType());
11899 FD->setType(T);
Douglas Gregor4581d452013-01-28 19:08:09 +000011900 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11901 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11902 // It's an error in ARC if a field has lifetime.
11903 // We don't want to report this in a system header, though,
11904 // so we just make the field unavailable.
11905 // FIXME: that's really not sufficient; we need to make the type
11906 // itself invalid to, say, initialize or copy.
11907 QualType T = FD->getType();
11908 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11909 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11910 SourceLocation loc = FD->getLocation();
11911 if (getSourceManager().isInSystemHeader(loc)) {
11912 if (!FD->hasAttr<UnavailableAttr>()) {
11913 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11914 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011915 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011916 } else {
11917 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregorbde67cf2013-01-28 20:13:44 +000011918 << T->isBlockPointerType() << Record->getTagKind();
John McCallf85e1932011-06-15 23:02:42 +000011919 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011920 ARCErrReported = true;
John McCallf85e1932011-06-15 23:02:42 +000011921 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011922 } else if (getLangOpts().ObjC1 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011923 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +000011924 Record && !Record->hasObjectMember()) {
Douglas Gregor4581d452013-01-28 19:08:09 +000011925 if (FD->getType()->isObjCObjectPointerType() ||
11926 FD->getType().isObjCGCStrong())
11927 Record->setHasObjectMember(true);
11928 else if (Context.getAsArrayType(FD->getType())) {
11929 QualType BaseType = Context.getBaseElementType(FD->getType());
11930 if (BaseType->isRecordType() &&
11931 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCallf85e1932011-06-15 23:02:42 +000011932 Record->setHasObjectMember(true);
Douglas Gregor4581d452013-01-28 19:08:09 +000011933 else if (BaseType->isObjCObjectPointerType() ||
11934 BaseType.isObjCGCStrong())
11935 Record->setHasObjectMember(true);
John McCallf85e1932011-06-15 23:02:42 +000011936 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +000011937 }
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011938 if (Record && FD->getType().isVolatileQualified())
11939 Record->setHasVolatileMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011940 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +000011941 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +000011942 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +000011943 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000011944
Reid Spencer5f016e22007-07-11 17:01:13 +000011945 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +000011946 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011947 bool Completed = false;
11948 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
11949 if (!CXXRecord->isInvalidDecl()) {
11950 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011951 for (CXXRecordDecl::conversion_iterator
11952 I = CXXRecord->conversion_begin(),
11953 E = CXXRecord->conversion_end(); I != E; ++I)
11954 I.setAccess((*I)->getAccess());
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011955
11956 if (!CXXRecord->isDependentType()) {
Peter Collingbournef51cfb82013-05-20 14:12:25 +000011957 if (CXXRecord->hasUserDeclaredDestructor()) {
11958 // Adjust user-defined destructor exception spec.
11959 if (getLangOpts().CPlusPlus11)
11960 AdjustDestructorExceptionSpec(CXXRecord,
11961 CXXRecord->getDestructor());
11962
11963 // The Microsoft ABI requires that we perform the destructor body
11964 // checks (i.e. operator delete() lookup) at every declaration, as
11965 // any translation unit may need to emit a deleting destructor.
11966 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11967 CheckDestructor(CXXRecord->getDestructor());
11968 }
Sebastian Redl0ee33912011-05-19 05:13:44 +000011969
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011970 // Add any implicitly-declared members to this class.
11971 AddImplicitlyDeclaredMembersToClass(CXXRecord);
11972
11973 // If we have virtual base classes, we may end up finding multiple
11974 // final overriders for a given virtual function. Check for this
11975 // problem now.
11976 if (CXXRecord->getNumVBases()) {
11977 CXXFinalOverriderMap FinalOverriders;
11978 CXXRecord->getFinalOverriders(FinalOverriders);
11979
11980 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
11981 MEnd = FinalOverriders.end();
11982 M != MEnd; ++M) {
11983 for (OverridingMethods::iterator SO = M->second.begin(),
11984 SOEnd = M->second.end();
11985 SO != SOEnd; ++SO) {
11986 assert(SO->second.size() > 0 &&
11987 "Virtual function without overridding functions?");
11988 if (SO->second.size() == 1)
11989 continue;
11990
11991 // C++ [class.virtual]p2:
11992 // In a derived class, if a virtual member function of a base
11993 // class subobject has more than one final overrider the
11994 // program is ill-formed.
11995 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divacky31ba6132012-09-06 15:59:27 +000011996 << (const NamedDecl *)M->first << Record;
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011997 Diag(M->first->getLocation(),
11998 diag::note_overridden_virtual_function);
11999 for (OverridingMethods::overriding_iterator
12000 OM = SO->second.begin(),
12001 OMEnd = SO->second.end();
12002 OM != OMEnd; ++OM)
12003 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divacky31ba6132012-09-06 15:59:27 +000012004 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012005
12006 Record->setInvalidDecl();
12007 }
12008 }
12009 CXXRecord->completeDefinition(&FinalOverriders);
12010 Completed = true;
12011 }
12012 }
12013 }
12014 }
12015
12016 if (!Completed)
12017 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +000012018
Richard Smithbe507b62013-02-01 08:12:08 +000012019 if (Record->hasAttrs())
12020 CheckAlignasUnderalignment(Record);
Serge Pavlov122e6012013-06-08 13:29:58 +000012021
12022 // Check if the structure/union declaration is a language extension.
12023 if (!getLangOpts().CPlusPlus) {
12024 bool ZeroSize = true;
Serge Pavlov0dcea352013-06-17 17:18:51 +000012025 bool IsEmpty = true;
12026 unsigned NonBitFields = 0;
Serge Pavlov122e6012013-06-08 13:29:58 +000012027 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlov0dcea352013-06-17 17:18:51 +000012028 E = Record->field_end();
12029 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12030 IsEmpty = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012031 if (I->isUnnamedBitfield()) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012032 if (I->getBitWidthValue(Context) > 0)
12033 ZeroSize = false;
12034 } else {
Serge Pavlov0dcea352013-06-17 17:18:51 +000012035 ++NonBitFields;
12036 QualType FieldType = I->getType();
12037 if (FieldType->isIncompleteType() ||
12038 !Context.getTypeSizeInChars(FieldType).isZero())
12039 ZeroSize = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012040 }
12041 }
12042
12043 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
12044 // C++.
Serge Pavlov0dcea352013-06-17 17:18:51 +000012045 if (ZeroSize)
12046 Diag(RecLoc, diag::warn_zero_size_struct_union_compat) << IsEmpty
12047 << Record->isUnion() << (NonBitFields > 1);
Serge Pavlov122e6012013-06-08 13:29:58 +000012048
12049 // Structs without named members are extension in C (C99 6.7.2.1p7), but
12050 // are accepted by GCC.
Serge Pavlov0dcea352013-06-17 17:18:51 +000012051 if (NonBitFields == 0) {
12052 if (IsEmpty)
Serge Pavlov122e6012013-06-08 13:29:58 +000012053 Diag(RecLoc, diag::ext_empty_struct_union) << Record->isUnion();
12054 else
12055 Diag(RecLoc, diag::ext_no_named_members_in_struct_union) << Record->isUnion();
12056 }
12057 }
Chris Lattnere1e79852008-02-06 00:51:33 +000012058 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +000012059 ObjCIvarDecl **ClsFields =
12060 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +000012061 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +000012062 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012063 // Add ivar's to class's DeclContext.
12064 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12065 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012066 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012067 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +000012068 // Must enforce the rule that ivars in the base classes may not be
12069 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +000012070 if (ID->getSuperClass())
12071 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +000012072 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +000012073 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000012074 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012075 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12076 // Ivar declared in @implementation never belongs to the implementation.
12077 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +000012078 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +000012079 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012080 IMPDecl->setIvarLBraceLoc(LBrac);
12081 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012082 } else if (ObjCCategoryDecl *CDecl =
12083 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012084 // case of ivars in class extension; all other cases have been
12085 // reported as errors elsewhere.
12086 // FIXME. Class extension does not have a LocEnd field.
12087 // CDecl->setLocEnd(RBrac);
12088 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012089 // Diagnose redeclaration of private ivars.
12090 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012091 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012092 if (IDecl) {
12093 if (const ObjCIvarDecl *ClsIvar =
12094 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12095 Diag(ClsFields[i]->getLocation(),
12096 diag::err_duplicate_ivar_declaration);
12097 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12098 continue;
12099 }
Douglas Gregord3297242013-01-16 23:00:23 +000012100 for (ObjCInterfaceDecl::known_extensions_iterator
12101 Ext = IDecl->known_extensions_begin(),
12102 ExtEnd = IDecl->known_extensions_end();
12103 Ext != ExtEnd; ++Ext) {
12104 if (const ObjCIvarDecl *ClsExtIvar
12105 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012106 Diag(ClsFields[i]->getLocation(),
12107 diag::err_duplicate_ivar_declaration);
12108 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12109 continue;
12110 }
12111 }
12112 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012113 ClsFields[i]->setLexicalDeclContext(CDecl);
12114 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012115 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012116 CDecl->setIvarLBraceLoc(LBrac);
12117 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +000012118 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +000012119 }
Daniel Dunbar7d076642008-10-03 17:33:35 +000012120
12121 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000012122 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +000012123}
12124
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012125/// \brief Determine whether the given integral value is representable within
12126/// the given type T.
12127static bool isRepresentableIntegerValue(ASTContext &Context,
12128 llvm::APSInt &Value,
12129 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012130 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +000012131 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012132
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012133 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +000012134 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012135 --BitWidth;
12136 return Value.getActiveBits() <= BitWidth;
12137 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012138 return Value.getMinSignedBits() <= BitWidth;
12139}
12140
12141// \brief Given an integral type, return the next larger integral type
12142// (or a NULL type of no such type exists).
12143static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12144 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12145 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012146 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012147 const unsigned NumTypes = 4;
12148 QualType SignedIntegralTypes[NumTypes] = {
12149 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12150 };
12151 QualType UnsignedIntegralTypes[NumTypes] = {
12152 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12153 Context.UnsignedLongLongTy
12154 };
12155
12156 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +000012157 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12158 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012159 for (unsigned I = 0; I != NumTypes; ++I)
12160 if (Context.getTypeSize(Types[I]) > BitWidth)
12161 return Types[I];
12162
12163 return QualType();
12164}
12165
Douglas Gregor879fd492009-03-17 19:05:46 +000012166EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12167 EnumConstantDecl *LastEnumConst,
12168 SourceLocation IdLoc,
12169 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +000012170 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012171 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012172 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +000012173 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +000012174
12175 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12176 Val = 0;
12177
Eli Friedman19efa3e2011-12-06 00:10:34 +000012178 if (Val)
12179 Val = DefaultLvalueConversion(Val).take();
12180
Douglas Gregor4912c342009-11-06 00:03:12 +000012181 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012182 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +000012183 EltTy = Context.DependentTy;
12184 else {
Douglas Gregor4912c342009-11-06 00:03:12 +000012185 SourceLocation ExpLoc;
Richard Smith80ad52f2013-01-02 11:42:31 +000012186 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012187 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012188 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12189 // constant-expression in the enumerator-definition shall be a converted
12190 // constant expression of the underlying type.
12191 EltTy = Enum->getIntegerType();
12192 ExprResult Converted =
12193 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12194 CCEK_Enumerator);
12195 if (Converted.isInvalid())
12196 Val = 0;
12197 else
12198 Val = Converted.take();
12199 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +000012200 !(Val = VerifyIntegerConstantExpression(Val,
12201 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012202 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +000012203 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012204 if (Enum->isFixed()) {
12205 EltTy = Enum->getIntegerType();
12206
Richard Smith8ef7b202012-01-18 23:55:52 +000012207 // In Obj-C and Microsoft mode, require the enumeration value to be
12208 // representable in the underlying type of the enumeration. In C++11,
12209 // we perform a non-narrowing conversion as part of converted constant
12210 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +000012211 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012212 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +000012213 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +000012214 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +000012215 } else
12216 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +000012217 } else
John Wiegley429bb272011-04-08 18:41:53 +000012218 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +000012219 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012220 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012221 // If the underlying type is not fixed, the type of each enumerator
12222 // is the type of its initializing value:
12223 // - If an initializer is specified for an enumerator, the
12224 // initializing value has the same type as the expression.
12225 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +000012226 } else {
12227 // C99 6.7.2.2p2:
12228 // The expression that defines the value of an enumeration constant
12229 // shall be an integer constant expression that has a value
12230 // representable as an int.
12231
12232 // Complain if the value is not representable in an int.
12233 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12234 Diag(IdLoc, diag::ext_enum_value_not_int)
12235 << EnumVal.toString(10) << Val->getSourceRange()
12236 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12237 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12238 // Force the type of the expression to 'int'.
12239 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12240 }
12241 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012242 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012243 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012244 }
12245 }
Mike Stump1eb44332009-09-09 15:08:12 +000012246
Douglas Gregor879fd492009-03-17 19:05:46 +000012247 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012248 if (Enum->isDependentType())
12249 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012250 else if (!LastEnumConst) {
12251 // C++0x [dcl.enum]p5:
12252 // If the underlying type is not fixed, the type of each enumerator
12253 // is the type of its initializing value:
12254 // - If no initializer is specified for the first enumerator, the
12255 // initializing value has an unspecified integral type.
12256 //
12257 // GCC uses 'int' for its unspecified integral type, as does
12258 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012259 if (Enum->isFixed()) {
12260 EltTy = Enum->getIntegerType();
12261 }
12262 else {
12263 EltTy = Context.IntTy;
12264 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012265 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000012266 // Assign the last value + 1.
12267 EnumVal = LastEnumConst->getInitVal();
12268 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012269 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000012270
12271 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012272 if (EnumVal < LastEnumConst->getInitVal()) {
12273 // C++0x [dcl.enum]p5:
12274 // If the underlying type is not fixed, the type of each enumerator
12275 // is the type of its initializing value:
12276 //
12277 // - Otherwise the type of the initializing value is the same as
12278 // the type of the initializing value of the preceding enumerator
12279 // unless the incremented value is not representable in that type,
12280 // in which case the type is an unspecified integral type
12281 // sufficient to contain the incremented value. If no such type
12282 // exists, the program is ill-formed.
12283 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012284 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012285 // There is no integral type larger enough to represent this
12286 // value. Complain, then allow the value to wrap around.
12287 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000012288 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012289 ++EnumVal;
12290 if (Enum->isFixed())
12291 // When the underlying type is fixed, this is ill-formed.
12292 Diag(IdLoc, diag::err_enumerator_wrapped)
12293 << EnumVal.toString(10)
12294 << EltTy;
12295 else
12296 Diag(IdLoc, diag::warn_enumerator_too_large)
12297 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012298 } else {
12299 EltTy = T;
12300 }
12301
12302 // Retrieve the last enumerator's value, extent that type to the
12303 // type that is supposed to be large enough to represent the incremented
12304 // value, then increment.
12305 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000012306 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000012307 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012308 ++EnumVal;
12309
12310 // If we're not in C++, diagnose the overflow of enumerator values,
12311 // which in C99 means that the enumerator value is not representable in
12312 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12313 // permits enumerator values that are representable in some larger
12314 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000012315 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012316 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000012317 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012318 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12319 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12320 Diag(IdLoc, diag::ext_enum_value_not_int)
12321 << EnumVal.toString(10) << 1;
12322 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012323 }
12324 }
Mike Stump1eb44332009-09-09 15:08:12 +000012325
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012326 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012327 // Make the enumerator value match the signedness and size of the
12328 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000012329 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000012330 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012331 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012332
Douglas Gregor879fd492009-03-17 19:05:46 +000012333 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000012334 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000012335}
12336
12337
John McCall5b629aa2010-10-22 23:36:17 +000012338Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12339 SourceLocation IdLoc, IdentifierInfo *Id,
12340 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000012341 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000012342 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000012343 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000012344 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000012345
Chris Lattner31e05722007-08-26 06:24:45 +000012346 // The scope passed in may not be a decl scope. Zip up the scope tree until
12347 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000012348 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000012349
Reid Spencer5f016e22007-07-11 17:01:13 +000012350 // Verify that there isn't already something declared with this name in this
12351 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000012352 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000012353 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000012354 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000012355 // Maybe we will complain about the shadowed template parameter.
12356 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12357 // Just pretend that we didn't see the previous declaration.
12358 PrevDecl = 0;
12359 }
12360
12361 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012362 // When in C++, we may get a TagDecl with the same name; in this case the
12363 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000012364 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012365 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000012366 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012367 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000012368 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000012369 else
Chris Lattner3c73c412008-11-19 08:23:25 +000012370 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000012371 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000012372 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000012373 }
12374 }
12375
Aaron Ballmanf8167872012-07-19 03:12:23 +000012376 // C++ [class.mem]p15:
12377 // If T is the name of a class, then each of the following shall have a name
12378 // different from T:
12379 // - every enumerator of every member of class T that is an unscoped
12380 // enumerated type
Douglas Gregora6e937c2010-10-15 13:21:21 +000012381 if (CXXRecordDecl *Record
12382 = dyn_cast<CXXRecordDecl>(
12383 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballmanf8167872012-07-19 03:12:23 +000012384 if (!TheEnumDecl->isScoped() &&
12385 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregora6e937c2010-10-15 13:21:21 +000012386 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12387
John McCall5b629aa2010-10-22 23:36:17 +000012388 EnumConstantDecl *New =
12389 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000012390
John McCall92f88312010-01-23 00:46:32 +000012391 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000012392 // Process attributes.
12393 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12394
12395 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000012396 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000012397 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000012398 }
Douglas Gregor45579f52008-12-17 02:04:30 +000012399
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000012400 ActOnDocumentableDecl(New);
12401
John McCalld226f652010-08-21 09:40:31 +000012402 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000012403}
12404
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012405// Returns true when the enum initial expression does not trigger the
12406// duplicate enum warning. A few common cases are exempted as follows:
12407// Element2 = Element1
12408// Element2 = Element1 + 1
12409// Element2 = Element1 - 1
12410// Where Element2 and Element1 are from the same enum.
12411static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12412 Expr *InitExpr = ECD->getInitExpr();
12413 if (!InitExpr)
12414 return true;
12415 InitExpr = InitExpr->IgnoreImpCasts();
12416
12417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12418 if (!BO->isAdditiveOp())
12419 return true;
12420 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12421 if (!IL)
12422 return true;
12423 if (IL->getValue() != 1)
12424 return true;
12425
12426 InitExpr = BO->getLHS();
12427 }
12428
12429 // This checks if the elements are from the same enum.
12430 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12431 if (!DRE)
12432 return true;
12433
12434 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12435 if (!EnumConstant)
12436 return true;
12437
12438 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12439 Enum)
12440 return true;
12441
12442 return false;
12443}
12444
12445struct DupKey {
12446 int64_t val;
12447 bool isTombstoneOrEmptyKey;
12448 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12449 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12450};
12451
12452static DupKey GetDupKey(const llvm::APSInt& Val) {
12453 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12454 false);
12455}
12456
12457struct DenseMapInfoDupKey {
12458 static DupKey getEmptyKey() { return DupKey(0, true); }
12459 static DupKey getTombstoneKey() { return DupKey(1, true); }
12460 static unsigned getHashValue(const DupKey Key) {
12461 return (unsigned)(Key.val * 37);
12462 }
12463 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12464 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12465 LHS.val == RHS.val;
12466 }
12467};
12468
12469// Emits a warning when an element is implicitly set a value that
12470// a previous element has already been set to.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012471static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12472 EnumDecl *Enum,
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012473 QualType EnumType) {
12474 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12475 Enum->getLocation()) ==
12476 DiagnosticsEngine::Ignored)
12477 return;
12478 // Avoid anonymous enums
12479 if (!Enum->getIdentifier())
12480 return;
12481
12482 // Only check for small enums.
12483 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12484 return;
12485
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012486 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12487 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012488
12489 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12490 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12491 ValueToVectorMap;
12492
12493 DuplicatesVector DupVector;
12494 ValueToVectorMap EnumMap;
12495
12496 // Populate the EnumMap with all values represented by enum constants without
12497 // an initialier.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012498 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramerefac8da2013-04-07 14:10:40 +000012499 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012500
12501 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12502 // this constant. Skip this enum since it may be ill-formed.
12503 if (!ECD) {
12504 return;
12505 }
12506
12507 if (ECD->getInitExpr())
12508 continue;
12509
12510 DupKey Key = GetDupKey(ECD->getInitVal());
12511 DeclOrVector &Entry = EnumMap[Key];
12512
12513 // First time encountering this value.
12514 if (Entry.isNull())
12515 Entry = ECD;
12516 }
12517
12518 // Create vectors for any values that has duplicates.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012519 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012520 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12521 if (!ValidDuplicateEnum(ECD, Enum))
12522 continue;
12523
12524 DupKey Key = GetDupKey(ECD->getInitVal());
12525
12526 DeclOrVector& Entry = EnumMap[Key];
12527 if (Entry.isNull())
12528 continue;
12529
12530 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12531 // Ensure constants are different.
12532 if (D == ECD)
12533 continue;
12534
12535 // Create new vector and push values onto it.
12536 ECDVector *Vec = new ECDVector();
12537 Vec->push_back(D);
12538 Vec->push_back(ECD);
12539
12540 // Update entry to point to the duplicates vector.
12541 Entry = Vec;
12542
12543 // Store the vector somewhere we can consult later for quick emission of
12544 // diagnostics.
12545 DupVector.push_back(Vec);
12546 continue;
12547 }
12548
12549 ECDVector *Vec = Entry.get<ECDVector*>();
12550 // Make sure constants are not added more than once.
12551 if (*Vec->begin() == ECD)
12552 continue;
12553
12554 Vec->push_back(ECD);
12555 }
12556
12557 // Emit diagnostics.
12558 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12559 DupVectorEnd = DupVector.end();
12560 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12561 ECDVector *Vec = *DupVectorIter;
12562 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12563
12564 // Emit warning for one enum constant.
12565 ECDVector::iterator I = Vec->begin();
12566 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12567 << (*I)->getName() << (*I)->getInitVal().toString(10)
12568 << (*I)->getSourceRange();
12569 ++I;
12570
12571 // Emit one note for each of the remaining enum constants with
12572 // the same value.
12573 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12574 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12575 << (*I)->getName() << (*I)->getInitVal().toString(10)
12576 << (*I)->getSourceRange();
12577 delete Vec;
12578 }
12579}
12580
Mike Stumpc6e35aa2009-05-16 07:06:02 +000012581void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000012582 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012583 ArrayRef<Decl *> Elements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012584 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000012585 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000012586 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012587
12588 if (Attr)
12589 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000012590
Eli Friedmaned0716b2009-12-11 01:34:50 +000012591 if (Enum->isDependentType()) {
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012592 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012593 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012594 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012595 if (!ECD) continue;
12596
12597 ECD->setType(EnumType);
12598 }
12599
John McCall1b5a6182010-05-06 08:49:23 +000012600 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012601 return;
12602 }
12603
Chris Lattnere37f0be2007-08-28 05:10:31 +000012604 // TODO: If the result value doesn't fit in an int, it must be a long or long
12605 // long value. ISO C does not support this, but GCC does as an extension,
12606 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012607 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12608 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12609 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012610
Chris Lattnerac609682007-08-28 06:15:15 +000012611 // Verify that all the values are okay, compute the size of the values, and
12612 // reverse the list.
12613 unsigned NumNegativeBits = 0;
12614 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000012615
Chris Lattnerac609682007-08-28 06:15:15 +000012616 // Keep track of whether all elements have type int.
12617 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000012618
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012619 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012620 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012621 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000012622 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000012623
Chris Lattner211a30e2007-08-28 05:27:00 +000012624 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000012625
Chris Lattnerac609682007-08-28 06:15:15 +000012626 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000012627 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000012628 NumPositiveBits = std::max(NumPositiveBits,
12629 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000012630 else
Chris Lattner21dd8212008-01-14 21:47:29 +000012631 NumNegativeBits = std::max(NumNegativeBits,
12632 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000012633
Chris Lattnerac609682007-08-28 06:15:15 +000012634 // Keep track of whether every enum element has type int (very commmon).
12635 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000012636 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000012637 }
Mike Stump1eb44332009-09-09 15:08:12 +000012638
Chris Lattnerac609682007-08-28 06:15:15 +000012639 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000012640 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012641 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012642
John McCall842aef82009-12-09 09:09:27 +000012643 // C++0x N3000 [conv.prom]p3:
12644 // An rvalue of an unscoped enumeration type whose underlying
12645 // type is not fixed can be converted to an rvalue of the first
12646 // of the following types that can represent all the values of
12647 // the enumeration: int, unsigned int, long int, unsigned long
12648 // int, long long int, or unsigned long long int.
12649 // C99 6.4.4.3p2:
12650 // An identifier declared as an enumeration constant has type int.
12651 // The C99 rule is modified by a gcc extension
12652 QualType BestPromotionType;
12653
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012654 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000012655 // -fshort-enums is the equivalent to specifying the packed attribute on all
12656 // enum definitions.
12657 if (LangOpts.ShortEnums)
12658 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012659
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012660 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000012661 BestType = Enum->getIntegerType();
12662 if (BestType->isPromotableIntegerType())
12663 BestPromotionType = Context.getPromotedIntegerType(BestType);
12664 else
12665 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000012666 // We don't need to set BestWidth, because BestType is going to be the type
12667 // of the enumerators, but we do anyway because otherwise some compilers
12668 // warn that it might be used uninitialized.
12669 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012670 }
12671 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000012672 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000012673 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012674 // If it's packed, check also if it fits a char or a short.
12675 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012676 BestType = Context.SignedCharTy;
12677 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000012678 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012679 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012680 BestType = Context.ShortTy;
12681 BestWidth = ShortWidth;
12682 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012683 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012684 BestWidth = IntWidth;
12685 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012686 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012687
John McCall842aef82009-12-09 09:09:27 +000012688 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012689 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000012690 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012691 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012692
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012693 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000012694 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12695 BestType = Context.LongLongTy;
12696 }
12697 }
John McCall842aef82009-12-09 09:09:27 +000012698 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000012699 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012700 // If there is no negative value, figure out the smallest type that fits
12701 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012702 // If it's packed, check also if it fits a char or a short.
12703 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012704 BestType = Context.UnsignedCharTy;
12705 BestPromotionType = Context.IntTy;
12706 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012707 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012708 BestType = Context.UnsignedShortTy;
12709 BestPromotionType = Context.IntTy;
12710 BestWidth = ShortWidth;
12711 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012712 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012713 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012714 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012715 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012716 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012717 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012718 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000012719 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012720 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012721 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012722 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000012723 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012724 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012725 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000012726 "How could an initializer get larger than ULL?");
12727 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012728 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012729 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012730 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000012731 }
12732 }
Mike Stump1eb44332009-09-09 15:08:12 +000012733
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012734 // Loop over all of the enumerator constants, changing their types to match
12735 // the type of the enum if needed.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012736 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +000012737 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012738 if (!ECD) continue; // Already issued a diagnostic.
12739
12740 // Standard C says the enumerators have int type, but we allow, as an
12741 // extension, the enumerators to be larger than int size. If each
12742 // enumerator value fits in an int, type it as an int, otherwise type it the
12743 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12744 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012745
12746 // Determine whether the value fits into an int.
12747 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012748
12749 // If it fits into an integer type, force it. Otherwise force it to match
12750 // the enum decl type.
12751 QualType NewTy;
12752 unsigned NewWidth;
12753 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000012754 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000012755 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012756 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012757 NewTy = Context.IntTy;
12758 NewWidth = IntWidth;
12759 NewSign = true;
12760 } else if (ECD->getType() == BestType) {
12761 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000012762 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012763 // C++ [dcl.enum]p4: Following the closing brace of an
12764 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012765 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012766 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012767 continue;
12768 } else {
12769 NewTy = BestType;
12770 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000012771 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012772 }
12773
12774 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000012775 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012776 InitVal.setIsSigned(NewSign);
12777 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000012778
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012779 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000012780 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000012781 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000012782 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000012783 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000012784 ECD->getInitExpr(),
12785 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000012786 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000012787 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012788 // C++ [dcl.enum]p4: Following the closing brace of an
12789 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012790 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012791 ECD->setType(EnumType);
12792 else
12793 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012794 }
Mike Stump1eb44332009-09-09 15:08:12 +000012795
John McCall1b5a6182010-05-06 08:49:23 +000012796 Enum->completeDefinition(BestType, BestPromotionType,
12797 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000012798
12799 // If we're declaring a function, ensure this decl isn't forgotten about -
12800 // it needs to go into the function scope.
12801 if (InFunctionDeclarator)
12802 DeclsInPrototypeScope.push_back(Enum);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012803
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012804 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smithbe507b62013-02-01 08:12:08 +000012805
12806 // Now that the enum type is defined, ensure it's not been underaligned.
12807 if (Enum->hasAttrs())
12808 CheckAlignasUnderalignment(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +000012809}
12810
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012811Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12812 SourceLocation StartLoc,
12813 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000012814 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000012815
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000012816 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012817 AsmString, StartLoc,
12818 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012819 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000012820 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000012821}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012822
Douglas Gregor5948ae12012-01-03 18:04:46 +000012823DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12824 SourceLocation ImportLoc,
12825 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000012826 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000012827 Module::AllVisible,
12828 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000012829 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012830 return true;
12831
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012832 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregor15de72c2011-12-02 23:23:56 +000012833 Module *ModCheck = Mod;
12834 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12835 // If we've run out of module parents, just drop the remaining identifiers.
12836 // We need the length to be consistent.
12837 if (!ModCheck)
12838 break;
12839 ModCheck = ModCheck->Parent;
12840
12841 IdentifierLocs.push_back(Path[I].second);
12842 }
12843
12844 ImportDecl *Import = ImportDecl::Create(Context,
12845 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000012846 AtLoc.isValid()? AtLoc : ImportLoc,
12847 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000012848 Context.getTranslationUnitDecl()->addDecl(Import);
12849 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012850}
12851
Douglas Gregorca2ab452013-01-12 01:29:50 +000012852void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12853 // Create the implicit import declaration.
12854 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12855 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12856 Loc, Mod, Loc);
12857 TU->addDecl(ImportD);
12858 Consumer.HandleImplicitImportDecl(ImportD);
12859
12860 // Make the module visible.
Douglas Gregor906d66a2013-03-20 21:10:35 +000012861 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12862 /*Complain=*/false);
Douglas Gregorca2ab452013-01-12 01:29:50 +000012863}
12864
David Chisnall5f3c1632012-02-18 16:12:34 +000012865void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12866 IdentifierInfo* AliasName,
12867 SourceLocation PragmaLoc,
12868 SourceLocation NameLoc,
12869 SourceLocation AliasNameLoc) {
12870 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12871 LookupOrdinaryName);
12872 AsmLabelAttr *Attr =
12873 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000012874
12875 if (PrevDecl)
12876 PrevDecl->addAttr(Attr);
12877 else
12878 (void)ExtnameUndeclaredIdentifiers.insert(
12879 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12880}
12881
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012882void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12883 SourceLocation PragmaLoc,
12884 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012885 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012886
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012887 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000012888 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000012889 } else {
12890 (void)WeakUndeclaredIdentifiers.insert(
12891 std::pair<IdentifierInfo*,WeakInfo>
12892 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012893 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012894}
12895
12896void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12897 IdentifierInfo* AliasName,
12898 SourceLocation PragmaLoc,
12899 SourceLocation NameLoc,
12900 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012901 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12902 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000012903 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012904
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012905 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000012906 if (!PrevDecl->hasAttr<AliasAttr>())
12907 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000012908 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000012909 } else {
12910 (void)WeakUndeclaredIdentifiers.insert(
12911 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012912 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012913}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000012914
12915Decl *Sema::getObjCDeclContext() const {
12916 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12917}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012918
12919AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000012920 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012921 return D->getAvailability();
12922}