blob: 222b70cdab8a3459ff5e8b92ac86c96345690840 [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
Warren Hunt2d023ec2013-11-01 23:46:51 +00001537 DeclContext *Parent = Context.getTranslationUnitDecl();
1538 if (getLangOpts().CPlusPlus) {
1539 LinkageSpecDecl *CLinkageDecl =
1540 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1541 LinkageSpecDecl::lang_c, false);
1542 Parent->addDecl(CLinkageDecl);
1543 Parent = CLinkageDecl;
1544 }
1545
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +00001546 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt2d023ec2013-11-01 23:46:51 +00001547 Parent,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001548 Loc, Loc, II, R, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001549 SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001550 false,
Douglas Gregor2224f842009-02-25 16:33:18 +00001551 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001552 New->setImplicit();
1553
Chris Lattner95e2c712008-05-05 22:18:14 +00001554 // Create Decl objects for each parameter, adding them to the
1555 // FunctionDecl.
John McCallf4c73712011-01-19 06:33:43 +00001556 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001557 SmallVector<ParmVarDecl*, 16> Params;
John McCallfb44de92011-05-01 22:35:37 +00001558 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1559 ParmVarDecl *parm =
1560 ParmVarDecl::Create(Context, New, SourceLocation(),
1561 SourceLocation(), 0,
1562 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001563 SC_None, 0);
John McCallfb44de92011-05-01 22:35:37 +00001564 parm->setScopeInfo(0, i);
1565 Params.push_back(parm);
1566 }
David Blaikie4278c652011-09-21 18:16:56 +00001567 New->setParams(Params);
Chris Lattner95e2c712008-05-05 22:18:14 +00001568 }
Mike Stump1eb44332009-09-09 15:08:12 +00001569
1570 AddKnownFunctionAttributes(New);
Warren Hunt2d023ec2013-11-01 23:46:51 +00001571 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Chris Lattner7f925cc2008-04-11 07:00:53 +00001573 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001574 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1575 // relate Scopes to DeclContexts, and probably eliminate CurContext
1576 // entirely, but we're not there yet.
1577 DeclContext *SavedContext = CurContext;
Warren Hunt2d023ec2013-11-01 23:46:51 +00001578 CurContext = Parent;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001579 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001580 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 return New;
1582}
1583
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001584/// \brief Filter out any previous declarations that the given declaration
1585/// should not consider because they are not permitted to conflict, e.g.,
1586/// because they come from hidden sub-modules and do not refer to the same
1587/// entity.
1588static void filterNonConflictingPreviousDecls(ASTContext &context,
1589 NamedDecl *decl,
1590 LookupResult &previous){
1591 // This is only interesting when modules are enabled.
1592 if (!context.getLangOpts().Modules)
1593 return;
1594
1595 // Empty sets are uninteresting.
1596 if (previous.empty())
1597 return;
1598
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001599 LookupResult::Filter filter = previous.makeFilter();
1600 while (filter.hasNext()) {
1601 NamedDecl *old = filter.next();
1602
1603 // Non-hidden declarations are never ignored.
1604 if (!old->isHidden())
1605 continue;
1606
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001607 if (!old->isExternallyVisible())
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001608 filter.erase();
1609 }
1610
1611 filter.done();
1612}
1613
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001614bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1615 QualType OldType;
1616 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1617 OldType = OldTypedef->getUnderlyingType();
1618 else
1619 OldType = Context.getTypeDeclType(Old);
1620 QualType NewType = New->getUnderlyingType();
1621
Douglas Gregorec3bd722012-01-11 22:33:48 +00001622 if (NewType->isVariablyModifiedType()) {
1623 // Must not redefine a typedef with a variably-modified type.
1624 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1625 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1626 << Kind << NewType;
1627 if (Old->getLocation().isValid())
1628 Diag(Old->getLocation(), diag::note_previous_definition);
1629 New->setInvalidDecl();
1630 return true;
1631 }
1632
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001633 if (OldType != NewType &&
1634 !OldType->isDependentType() &&
1635 !NewType->isDependentType() &&
Douglas Gregorec3bd722012-01-11 22:33:48 +00001636 !Context.hasSameType(OldType, NewType)) {
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001637 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1638 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1639 << Kind << NewType << OldType;
1640 if (Old->getLocation().isValid())
1641 Diag(Old->getLocation(), diag::note_previous_definition);
1642 New->setInvalidDecl();
1643 return true;
1644 }
1645 return false;
1646}
1647
Richard Smith162e1c12011-04-15 14:24:37 +00001648/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregorcda9c672009-02-16 17:45:42 +00001649/// same name and scope as a previous declaration 'Old'. Figure out
1650/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +00001651/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001652///
Richard Smith162e1c12011-04-15 14:24:37 +00001653void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall68263142009-11-18 22:49:29 +00001654 // If the new decl is known invalid already, don't bother doing any
1655 // merging checks.
1656 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Steve Naroff2b255c42008-09-09 14:32:20 +00001658 // Allow multiple definitions for ObjC built-in typedefs.
1659 // FIXME: Verify the underlying types are equivalent!
David Blaikie4e4d0842012-03-11 07:00:24 +00001660 if (getLangOpts().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +00001661 const IdentifierInfo *TypeID = New->getIdentifier();
1662 switch (TypeID->getLength()) {
1663 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +00001664 case 2:
Fariborz Jahanian0cd00be2012-05-14 22:48:56 +00001665 {
1666 if (!TypeID->isStr("id"))
1667 break;
1668 QualType T = New->getUnderlyingType();
1669 if (!T->isPointerType())
1670 break;
1671 if (!T->isVoidPointerType()) {
1672 QualType PT = T->getAs<PointerType>()->getPointeeType();
1673 if (!PT->isStructureType())
1674 break;
1675 }
1676 Context.setObjCIdRedefinitionType(T);
1677 // Install the built-in type for 'id', ignoring the current definition.
1678 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1679 return;
1680 }
Chris Lattner2bac0f62008-11-20 05:41:43 +00001681 case 5:
1682 if (!TypeID->isStr("Class"))
1683 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001684 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff14108da2009-07-10 23:34:53 +00001685 // Install the built-in type for 'Class', ignoring the current definition.
1686 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001687 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +00001688 case 3:
1689 if (!TypeID->isStr("SEL"))
1690 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001691 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001692 // Install the built-in type for 'SEL', ignoring the current definition.
1693 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001694 return;
Steve Naroff2b255c42008-09-09 14:32:20 +00001695 }
1696 // Fall through - the typedef name was not a builtin type.
1697 }
John McCall68263142009-11-18 22:49:29 +00001698
Douglas Gregor66973122009-01-28 17:15:10 +00001699 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +00001700 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1701 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +00001702 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001703 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001704
1705 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001706 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00001707 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +00001708
Chris Lattnereaaebc72009-04-25 08:06:05 +00001709 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 }
Douglas Gregor66973122009-01-28 17:15:10 +00001711
John McCall68263142009-11-18 22:49:29 +00001712 // If the old declaration is invalid, just give up here.
1713 if (Old->isInvalidDecl())
1714 return New->setInvalidDecl();
1715
Chris Lattner99cb9972008-07-25 18:44:27 +00001716 // If the typedef types are not identical, reject them in all languages and
1717 // with any extensions enabled.
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001718 if (isIncompatibleTypedef(Old, New))
1719 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Justin Bogner2dd68de2013-10-08 00:19:09 +00001721 // The types match. Link up the redeclaration chain and merge attributes if
1722 // the old declaration was a typedef.
1723 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001724 New->setPreviousDecl(Typedef);
Justin Bogner2dd68de2013-10-08 00:19:09 +00001725 mergeDeclAttributes(New, Old);
1726 }
Eli Friedman9ec40992013-07-16 02:07:49 +00001727
David Blaikie4e4d0842012-03-11 07:00:24 +00001728 if (getLangOpts().MicrosoftExt)
Chris Lattnereaaebc72009-04-25 08:06:05 +00001729 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +00001730
David Blaikie4e4d0842012-03-11 07:00:24 +00001731 if (getLangOpts().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +00001732 // C++ [dcl.typedef]p2:
1733 // In a given non-class scope, a typedef specifier can be used to
1734 // redefine the name of any type declared in that scope to refer
1735 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +00001736 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +00001737 return;
Douglas Gregor93dda722010-01-11 21:54:40 +00001738
1739 // C++0x [dcl.typedef]p4:
1740 // In a given class scope, a typedef specifier can be used to redefine
1741 // any class-name declared in that scope that is not also a typedef-name
1742 // to refer to the type to which it already refers.
1743 //
1744 // This wording came in via DR424, which was a correction to the
1745 // wording in DR56, which accidentally banned code like:
1746 //
1747 // struct S {
1748 // typedef struct A { } A;
1749 // };
1750 //
1751 // in the C++03 standard. We implement the C++0x semantics, which
1752 // allow the above but disallow
1753 //
1754 // struct S {
1755 // typedef int I;
1756 // typedef int I;
1757 // };
1758 //
1759 // since that was the intent of DR56.
Richard Smith162e1c12011-04-15 14:24:37 +00001760 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +00001761 return;
1762
Chris Lattner32b06752009-04-17 22:04:20 +00001763 Diag(New->getLocation(), diag::err_redefinition)
1764 << New->getDeclName();
1765 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001766 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +00001767 }
Eli Friedman54ecfce2008-06-11 06:20:39 +00001768
Douglas Gregorc0004df2012-01-11 04:25:01 +00001769 // Modules always permit redefinition of typedefs, as does C11.
David Blaikie4e4d0842012-03-11 07:00:24 +00001770 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregorc02d62f2012-01-09 15:36:04 +00001771 return;
1772
Chris Lattner32b06752009-04-17 22:04:20 +00001773 // If we have a redefinition of a typedef in C, emit a warning. This warning
1774 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +00001775 // -Wtypedef-redefinition. If either the original or the redefinition is
1776 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00001777 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +00001778 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1779 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +00001780 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Chris Lattner32b06752009-04-17 22:04:20 +00001782 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1783 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001784 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001785 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001786}
1787
Chris Lattner6b6b5372008-06-26 18:38:35 +00001788/// DeclhasAttr - returns true if decl Declaration already has the target
1789/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00001790static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001791DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola3b294362012-05-06 19:56:25 +00001792 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1793 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1794 // responsible for making sure they are consistent.
1795 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1796 if (AA)
1797 return false;
1798
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001799 // The following thread safety attributes can also be duplicated.
1800 switch (A->getKind()) {
1801 case attr::ExclusiveLocksRequired:
1802 case attr::SharedLocksRequired:
1803 case attr::LocksExcluded:
1804 case attr::ExclusiveLockFunction:
1805 case attr::SharedLockFunction:
1806 case attr::UnlockFunction:
1807 case attr::ExclusiveTrylockFunction:
1808 case attr::SharedTrylockFunction:
1809 case attr::GuardedBy:
1810 case attr::PtGuardedBy:
1811 case attr::AcquiredBefore:
1812 case attr::AcquiredAfter:
1813 return false;
DeLesley Hutchins6c500b12012-10-12 21:49:04 +00001814 default:
1815 ;
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001816 }
1817
Sean Huntcf807c42010-08-18 23:23:40 +00001818 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001819 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Sean Huntcf807c42010-08-18 23:23:40 +00001820 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1821 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001822 if (Ann) {
1823 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1824 return true;
1825 continue;
1826 }
Sean Huntcf807c42010-08-18 23:23:40 +00001827 // FIXME: Don't hardcode this check
1828 if (OA && isa<OwnershipAttr>(*i))
1829 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001830 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001831 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001832
1833 return false;
1834}
1835
Richard Smith671b3212013-02-22 04:55:39 +00001836static bool isAttributeTargetADefinition(Decl *D) {
1837 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1838 return VD->isThisDeclarationADefinition();
1839 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1840 return TD->isCompleteDefinition() || TD->isBeingDefined();
1841 return true;
1842}
1843
1844/// Merge alignment attributes from \p Old to \p New, taking into account the
1845/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1846///
1847/// \return \c true if any attributes were added to \p New.
1848static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1849 // Look for alignas attributes on Old, and pick out whichever attribute
1850 // specifies the strictest alignment requirement.
1851 AlignedAttr *OldAlignasAttr = 0;
1852 AlignedAttr *OldStrictestAlignAttr = 0;
1853 unsigned OldAlign = 0;
1854 for (specific_attr_iterator<AlignedAttr>
1855 I = Old->specific_attr_begin<AlignedAttr>(),
1856 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1857 // FIXME: We have no way of representing inherited dependent alignments
1858 // in a case like:
1859 // template<int A, int B> struct alignas(A) X;
1860 // template<int A, int B> struct alignas(B) X {};
1861 // For now, we just ignore any alignas attributes which are not on the
1862 // definition in such a case.
1863 if (I->isAlignmentDependent())
1864 return false;
1865
1866 if (I->isAlignas())
1867 OldAlignasAttr = *I;
1868
1869 unsigned Align = I->getAlignment(S.Context);
1870 if (Align > OldAlign) {
1871 OldAlign = Align;
1872 OldStrictestAlignAttr = *I;
1873 }
1874 }
1875
1876 // Look for alignas attributes on New.
1877 AlignedAttr *NewAlignasAttr = 0;
1878 unsigned NewAlign = 0;
1879 for (specific_attr_iterator<AlignedAttr>
1880 I = New->specific_attr_begin<AlignedAttr>(),
1881 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1882 if (I->isAlignmentDependent())
1883 return false;
1884
1885 if (I->isAlignas())
1886 NewAlignasAttr = *I;
1887
1888 unsigned Align = I->getAlignment(S.Context);
1889 if (Align > NewAlign)
1890 NewAlign = Align;
1891 }
1892
1893 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1894 // Both declarations have 'alignas' attributes. We require them to match.
1895 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1896 // fall short. (If two declarations both have alignas, they must both match
1897 // every definition, and so must match each other if there is a definition.)
1898
1899 // If either declaration only contains 'alignas(0)' specifiers, then it
1900 // specifies the natural alignment for the type.
1901 if (OldAlign == 0 || NewAlign == 0) {
1902 QualType Ty;
1903 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1904 Ty = VD->getType();
1905 else
1906 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1907
1908 if (OldAlign == 0)
1909 OldAlign = S.Context.getTypeAlign(Ty);
1910 if (NewAlign == 0)
1911 NewAlign = S.Context.getTypeAlign(Ty);
1912 }
1913
1914 if (OldAlign != NewAlign) {
1915 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1916 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1917 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1918 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1919 }
1920 }
1921
1922 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1923 // C++11 [dcl.align]p6:
1924 // if any declaration of an entity has an alignment-specifier,
1925 // every defining declaration of that entity shall specify an
1926 // equivalent alignment.
1927 // C11 6.7.5/7:
1928 // If the definition of an object does not have an alignment
1929 // specifier, any other declaration of that object shall also
1930 // have no alignment specifier.
1931 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1932 << OldAlignasAttr->isC11();
1933 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1934 << OldAlignasAttr->isC11();
1935 }
1936
1937 bool AnyAdded = false;
1938
1939 // Ensure we have an attribute representing the strictest alignment.
1940 if (OldAlign > NewAlign) {
1941 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1942 Clone->setInherited(true);
1943 New->addAttr(Clone);
1944 AnyAdded = true;
1945 }
1946
1947 // Ensure we have an alignas attribute if the old declaration had one.
1948 if (OldAlignasAttr && !NewAlignasAttr &&
1949 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1950 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1951 Clone->setInherited(true);
1952 New->addAttr(Clone);
1953 AnyAdded = true;
1954 }
1955
1956 return AnyAdded;
1957}
1958
1959static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1960 bool Override) {
Rafael Espindola599f1b72012-05-13 03:25:18 +00001961 InheritableAttr *NewAttr = NULL;
Michael Han51d8c522013-01-24 16:46:58 +00001962 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola838dc592013-01-12 06:42:30 +00001963 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001964 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1965 AA->getIntroduced(), AA->getDeprecated(),
1966 AA->getObsoleted(), AA->getUnavailable(),
1967 AA->getMessage(), Override,
John McCalld4c3d662013-02-20 01:54:26 +00001968 AttrSpellingListIndex);
Richard Smith671b3212013-02-22 04:55:39 +00001969 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1970 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1971 AttrSpellingListIndex);
1972 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1973 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1974 AttrSpellingListIndex);
Rafael Espindola838dc592013-01-12 06:42:30 +00001975 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001976 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1977 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001978 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001979 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1980 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001981 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001982 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1983 FA->getFormatIdx(), FA->getFirstArg(),
1984 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001985 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001986 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1987 AttrSpellingListIndex);
1988 else if (isa<AlignedAttr>(Attr))
1989 // AlignedAttrs are handled separately, because we need to handle all
1990 // such attributes on a declaration at the same time.
1991 NewAttr = 0;
Rafael Espindola599f1b72012-05-13 03:25:18 +00001992 else if (!DeclHasAttr(D, Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001993 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindola98ae8342012-05-10 02:50:16 +00001994
Rafael Espindola599f1b72012-05-13 03:25:18 +00001995 if (NewAttr) {
Rafael Espindola98ae8342012-05-10 02:50:16 +00001996 NewAttr->setInherited(true);
1997 D->addAttr(NewAttr);
1998 return true;
1999 }
2000
2001 return false;
2002}
2003
Rafael Espindola4b044c62012-07-15 01:05:36 +00002004static const Decl *getDefinition(const Decl *D) {
2005 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola3f664062012-05-18 01:47:00 +00002006 return TD->getDefinition();
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002007 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2008 const VarDecl *Def = VD->getDefinition();
2009 if (Def)
2010 return Def;
2011 return VD->getActingDefinition();
2012 }
Rafael Espindola4b044c62012-07-15 01:05:36 +00002013 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola3f664062012-05-18 01:47:00 +00002014 const FunctionDecl* Def;
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002015 if (FD->isDefined(Def))
Rafael Espindola3f664062012-05-18 01:47:00 +00002016 return Def;
2017 }
2018 return NULL;
2019}
2020
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002021static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2022 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2023 I != E; ++I) {
2024 Attr *Attribute = *I;
2025 if (Attribute->getKind() == Kind)
2026 return true;
2027 }
2028 return false;
2029}
2030
2031/// checkNewAttributesAfterDef - If we already have a definition, check that
2032/// there are no new attributes in this declaration.
2033static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2034 if (!New->hasAttrs())
2035 return;
2036
2037 const Decl *Def = getDefinition(Old);
2038 if (!Def || Def == New)
2039 return;
2040
2041 AttrVec &NewAttributes = New->getAttrs();
2042 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2043 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002044
2045 if (isa<AliasAttr>(NewAttribute)) {
2046 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2047 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2048 else {
2049 VarDecl *VD = cast<VarDecl>(New);
2050 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2051 VarDecl::TentativeDefinition
2052 ? diag::err_alias_after_tentative
2053 : diag::err_redefinition;
2054 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2055 S.Diag(Def->getLocation(), diag::note_previous_definition);
2056 VD->setInvalidDecl();
2057 }
2058 ++I;
2059 continue;
2060 }
2061
2062 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2063 // Tentative definitions are only interesting for the alias check above.
2064 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2065 ++I;
2066 continue;
2067 }
2068 }
2069
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002070 if (hasAttribute(Def, NewAttribute->getKind())) {
2071 ++I;
2072 continue; // regular attr merging will take care of validating this.
2073 }
Richard Smith671b3212013-02-22 04:55:39 +00002074
Richard Smith7586a6e2013-01-30 05:45:05 +00002075 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smith671b3212013-02-22 04:55:39 +00002076 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smith7586a6e2013-01-30 05:45:05 +00002077 ++I;
2078 continue;
Richard Smith671b3212013-02-22 04:55:39 +00002079 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2080 if (AA->isAlignas()) {
2081 // C++11 [dcl.align]p6:
2082 // if any declaration of an entity has an alignment-specifier,
2083 // every defining declaration of that entity shall specify an
2084 // equivalent alignment.
2085 // C11 6.7.5/7:
2086 // If the definition of an object does not have an alignment
2087 // specifier, any other declaration of that object shall also
2088 // have no alignment specifier.
2089 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2090 << AA->isC11();
2091 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2092 << AA->isC11();
2093 NewAttributes.erase(NewAttributes.begin() + I);
2094 --E;
2095 continue;
2096 }
Richard Smith7586a6e2013-01-30 05:45:05 +00002097 }
Richard Smith671b3212013-02-22 04:55:39 +00002098
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002099 S.Diag(NewAttribute->getLocation(),
2100 diag::warn_attribute_precede_definition);
2101 S.Diag(Def->getLocation(), diag::note_previous_definition);
2102 NewAttributes.erase(NewAttributes.begin() + I);
2103 --E;
2104 }
2105}
2106
John McCalleca5d222011-03-02 04:00:57 +00002107/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindola51be6e32013-01-08 22:04:34 +00002108void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002109 AvailabilityMergeKind AMK) {
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002110 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2111 UsedAttr *NewAttr = OldAttr->clone(Context);
2112 NewAttr->setInherited(true);
2113 New->addAttr(NewAttr);
2114 }
2115
Richard Smith3a2b7a12013-01-28 22:42:45 +00002116 if (!Old->hasAttrs() && !New->hasAttrs())
2117 return;
2118
Rafael Espindola3f664062012-05-18 01:47:00 +00002119 // attributes declared post-definition are currently ignored
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002120 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola3f664062012-05-18 01:47:00 +00002121
Douglas Gregor27c6da22012-01-01 20:30:41 +00002122 if (!Old->hasAttrs())
Sean Huntcf807c42010-08-18 23:23:40 +00002123 return;
John McCalleca5d222011-03-02 04:00:57 +00002124
Douglas Gregor27c6da22012-01-01 20:30:41 +00002125 bool foundAny = New->hasAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002126
Sean Huntcf807c42010-08-18 23:23:40 +00002127 // Ensure that any moving of objects within the allocated map is done before
2128 // we process them.
Douglas Gregor27c6da22012-01-01 20:30:41 +00002129 if (!foundAny) New->setAttrs(AttrVec());
John McCalleca5d222011-03-02 04:00:57 +00002130
Peter Collingbournea97d70b2011-01-21 02:08:36 +00002131 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor27c6da22012-01-01 20:30:41 +00002132 i = Old->specific_attr_begin<InheritableAttr>(),
2133 e = Old->specific_attr_end<InheritableAttr>();
2134 i != e; ++i) {
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002135 bool Override = false;
Douglas Gregorc193dd82011-09-23 20:23:42 +00002136 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002137 if (isa<DeprecatedAttr>(*i) ||
2138 isa<UnavailableAttr>(*i) ||
2139 isa<AvailabilityAttr>(*i)) {
2140 switch (AMK) {
2141 case AMK_None:
2142 continue;
John McCall6c2c2502011-07-22 02:45:48 +00002143
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002144 case AMK_Redeclaration:
2145 break;
2146
2147 case AMK_Override:
2148 Override = true;
2149 break;
2150 }
2151 }
2152
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002153 // Already handled.
2154 if (isa<UsedAttr>(*i))
2155 continue;
2156
Richard Smith671b3212013-02-22 04:55:39 +00002157 if (mergeDeclAttribute(*this, New, *i, Override))
John McCalleca5d222011-03-02 04:00:57 +00002158 foundAny = true;
Chris Lattnerddee4232008-03-03 03:28:21 +00002159 }
John McCalleca5d222011-03-02 04:00:57 +00002160
Richard Smith671b3212013-02-22 04:55:39 +00002161 if (mergeAlignedAttrs(*this, New, Old))
2162 foundAny = true;
2163
Douglas Gregor27c6da22012-01-01 20:30:41 +00002164 if (!foundAny) New->dropAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002165}
2166
2167/// mergeParamDeclAttributes - Copy attributes from the old parameter
2168/// to the new one.
2169static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2170 const ParmVarDecl *oldDecl,
Richard Smith3a2b7a12013-01-28 22:42:45 +00002171 Sema &S) {
2172 // C++11 [dcl.attr.depend]p2:
2173 // The first declaration of a function shall specify the
2174 // carries_dependency attribute for its declarator-id if any declaration
2175 // of the function specifies the carries_dependency attribute.
2176 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2177 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2178 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2179 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2180 // Find the first declaration of the parameter.
2181 // FIXME: Should we build redeclaration chains for function parameters?
2182 const FunctionDecl *FirstFD =
Rafael Espindolabc650912013-10-17 15:37:26 +00002183 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smith3a2b7a12013-01-28 22:42:45 +00002184 const ParmVarDecl *FirstVD =
2185 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2186 S.Diag(FirstVD->getLocation(),
2187 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2188 }
2189
John McCalleca5d222011-03-02 04:00:57 +00002190 if (!oldDecl->hasAttrs())
2191 return;
2192
2193 bool foundAny = newDecl->hasAttrs();
2194
2195 // Ensure that any moving of objects within the allocated map is
2196 // done before we process them.
2197 if (!foundAny) newDecl->setAttrs(AttrVec());
2198
2199 for (specific_attr_iterator<InheritableParamAttr>
2200 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2201 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2202 if (!DeclHasAttr(newDecl, *i)) {
Richard Smith3a2b7a12013-01-28 22:42:45 +00002203 InheritableAttr *newAttr =
2204 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCalleca5d222011-03-02 04:00:57 +00002205 newAttr->setInherited(true);
2206 newDecl->addAttr(newAttr);
2207 foundAny = true;
2208 }
2209 }
2210
2211 if (!foundAny) newDecl->dropAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +00002212}
2213
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002214namespace {
2215
Douglas Gregorc8376562009-03-06 22:43:54 +00002216/// Used in MergeFunctionDecl to keep track of function parameters in
2217/// C.
2218struct GNUCompatibleParamWarning {
2219 ParmVarDecl *OldParm;
2220 ParmVarDecl *NewParm;
2221 QualType PromotedType;
2222};
2223
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002224}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002225
2226/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002227Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002228 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Sean Huntf961ea52011-05-10 19:08:14 +00002229 if (Ctor->isDefaultConstructor())
2230 return Sema::CXXDefaultConstructor;
Sean Hunt9ae60d52011-05-26 01:26:05 +00002231
2232 if (Ctor->isCopyConstructor())
2233 return Sema::CXXCopyConstructor;
2234
2235 if (Ctor->isMoveConstructor())
2236 return Sema::CXXMoveConstructor;
Sean Hunt82713172011-05-25 23:16:36 +00002237 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002238 return Sema::CXXDestructor;
Sean Hunt82713172011-05-25 23:16:36 +00002239 } else if (MD->isCopyAssignmentOperator()) {
Sean Huntf961ea52011-05-10 19:08:14 +00002240 return Sema::CXXCopyAssignment;
Sebastian Redl74e611a2011-09-04 18:14:28 +00002241 } else if (MD->isMoveAssignmentOperator()) {
2242 return Sema::CXXMoveAssignment;
Sean Hunt82713172011-05-25 23:16:36 +00002243 }
Sean Huntf961ea52011-05-10 19:08:14 +00002244
Sean Huntf961ea52011-05-10 19:08:14 +00002245 return Sema::CXXInvalid;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002246}
2247
Sebastian Redl515ddd82010-06-09 21:17:41 +00002248/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002249/// only extern inline functions can be redefined, and even then only in
2250/// GNU89 mode.
2251static bool canRedefineFunction(const FunctionDecl *FD,
2252 const LangOptions& LangOpts) {
Eli Friedmaneca3ed72011-06-13 23:56:42 +00002253 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2254 !LangOpts.CPlusPlus &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002255 FD->isInlineSpecified() &&
John McCalld931b082010-08-26 03:08:43 +00002256 FD->getStorageClass() == SC_Extern);
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002257}
2258
Reid Kleckneref072032013-08-27 23:08:25 +00002259const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2260 const AttributedType *AT = T->getAs<AttributedType>();
2261 while (AT && !AT->isCallingConv())
2262 AT = AT->getModifiedType()->getAs<AttributedType>();
2263 return AT;
John McCallfb609142012-08-25 02:00:03 +00002264}
2265
Benjamin Kramera574c892013-02-15 12:30:38 +00002266template <typename T>
2267static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindola950fee22013-02-14 01:18:37 +00002268 const DeclContext *DC = Old->getDeclContext();
2269 if (DC->isRecord())
2270 return false;
2271
2272 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002273 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002274 return true;
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002275 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002276 return true;
2277 return false;
2278}
2279
Chris Lattner04421082008-04-08 04:40:51 +00002280/// MergeFunctionDecl - We just parsed a function 'New' from
2281/// declarator D which has the same name and scope as a previous
2282/// declaration 'Old'. Figure out how to resolve this situation,
2283/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002284///
2285/// In C++, New and Old must be declarations that are not
2286/// overloaded. Use IsOverload to determine whether New and Old are
2287/// overloaded, and to select the Old declaration that New should be
2288/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002289///
2290/// Returns true if there was an error, false otherwise.
Richard Smithdd9459f2013-08-13 18:18:50 +00002291bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2292 bool MergeTypeWithOld) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002294 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002295 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00002296 = dyn_cast<FunctionTemplateDecl>(OldD))
2297 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002298 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002299 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00002301 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCall78037ac2013-04-03 21:19:47 +00002302 if (New->getFriendObjectKind()) {
2303 Diag(New->getLocation(), diag::err_using_decl_friend);
2304 Diag(Shadow->getTargetDecl()->getLocation(),
2305 diag::note_using_decl_target);
2306 Diag(Shadow->getUsingDecl()->getLocation(),
2307 diag::note_using_decl) << 0;
2308 return true;
2309 }
2310
John McCall41ce66f2009-12-10 19:51:03 +00002311 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2312 Diag(Shadow->getTargetDecl()->getLocation(),
2313 diag::note_using_decl_target);
2314 Diag(Shadow->getUsingDecl()->getLocation(),
2315 diag::note_using_decl) << 0;
2316 return true;
2317 }
2318
Chris Lattner5dc266a2008-11-20 06:13:02 +00002319 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002320 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002321 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00002322 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002324
David Majnemerbcd06502013-07-07 23:49:50 +00002325 // If the old declaration is invalid, just give up here.
2326 if (Old->isInvalidDecl())
2327 return true;
2328
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002329 // Determine whether the previous declaration was a definition,
2330 // implicit declaration, or a declaration.
2331 diag::kind PrevDiag;
2332 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00002333 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002334 else if (Old->isImplicit())
2335 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002336 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00002337 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002339 // Don't complain about this if we're in GNU89 mode and the old function
2340 // is an extern inline function.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002341 // Don't complain about specializations. They are not supposed to have
2342 // storage classes.
Douglas Gregor04495c82009-02-24 01:23:02 +00002343 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCalld931b082010-08-26 03:08:43 +00002344 New->getStorageClass() == SC_Static &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00002345 Old->hasExternalFormalLinkage() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002346 !New->getTemplateSpecializationInfo() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002347 !canRedefineFunction(Old, getLangOpts())) {
2348 if (getLangOpts().MicrosoftExt) {
Francois Pichet4bada2e2011-04-22 19:50:06 +00002349 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2350 Diag(Old->getLocation(), PrevDiag);
2351 } else {
2352 Diag(New->getLocation(), diag::err_static_non_static) << New;
2353 Diag(Old->getLocation(), PrevDiag);
2354 return true;
2355 }
Douglas Gregor04495c82009-02-24 01:23:02 +00002356 }
2357
Reid Kleckneref072032013-08-27 23:08:25 +00002358
2359 // If a function is first declared with a calling convention, but is later
2360 // declared or defined without one, all following decls assume the calling
2361 // convention of the first.
John McCallf82b4e82010-02-04 05:44:44 +00002362 //
John McCallfb609142012-08-25 02:00:03 +00002363 // It's OK if a function is first declared without a calling convention,
2364 // but is later declared or defined with the default calling convention.
2365 //
Reid Kleckneref072032013-08-27 23:08:25 +00002366 // To test if either decl has an explicit calling convention, we look for
2367 // AttributedType sugar nodes on the type as written. If they are missing or
2368 // were canonicalized away, we assume the calling convention was implicit.
John McCallf82b4e82010-02-04 05:44:44 +00002369 //
2370 // Note also that we DO NOT return at this point, because we still have
2371 // other tests to run.
Reid Kleckneref072032013-08-27 23:08:25 +00002372 QualType OldQType = Context.getCanonicalType(Old->getType());
2373 QualType NewQType = Context.getCanonicalType(New->getType());
John McCalle6a365d2010-12-19 02:44:49 +00002374 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckneref072032013-08-27 23:08:25 +00002375 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCalle6a365d2010-12-19 02:44:49 +00002376 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2377 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2378 bool RequiresAdjustment = false;
John McCallfb609142012-08-25 02:00:03 +00002379
Reid Kleckneref072032013-08-27 23:08:25 +00002380 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindolabc650912013-10-17 15:37:26 +00002381 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckneref072032013-08-27 23:08:25 +00002382 const FunctionType *FT =
2383 First->getType().getCanonicalType()->castAs<FunctionType>();
2384 FunctionType::ExtInfo FI = FT->getExtInfo();
2385 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2386 if (!NewCCExplicit) {
2387 // Inherit the CC from the previous declaration if it was specified
2388 // there but not here.
2389 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2390 RequiresAdjustment = true;
2391 } else {
2392 // Calling conventions aren't compatible, so complain.
2393 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2394 Diag(New->getLocation(), diag::err_cconv_change)
2395 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2396 << !FirstCCExplicit
2397 << (!FirstCCExplicit ? "" :
2398 FunctionType::getNameForCallConv(FI.getCC()));
John McCallfb609142012-08-25 02:00:03 +00002399
Reid Kleckneref072032013-08-27 23:08:25 +00002400 // Put the note on the first decl, since it is the one that matters.
2401 Diag(First->getLocation(), diag::note_previous_declaration);
2402 return true;
2403 }
John McCallf82b4e82010-02-04 05:44:44 +00002404 }
2405
John McCall04a67a62010-02-05 21:31:56 +00002406 // FIXME: diagnose the other way around?
John McCalle6a365d2010-12-19 02:44:49 +00002407 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2408 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2409 RequiresAdjustment = true;
John McCall04a67a62010-02-05 21:31:56 +00002410 }
2411
Douglas Gregord2c64902010-06-18 21:30:25 +00002412 // Merge regparm attribute.
Eli Friedmana49218e2011-04-09 08:18:08 +00002413 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2414 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2415 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregord2c64902010-06-18 21:30:25 +00002416 Diag(New->getLocation(), diag::err_regparm_mismatch)
2417 << NewType->getRegParmType()
2418 << OldType->getRegParmType();
2419 Diag(Old->getLocation(), diag::note_previous_declaration);
2420 return true;
2421 }
John McCalle6a365d2010-12-19 02:44:49 +00002422
2423 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2424 RequiresAdjustment = true;
2425 }
2426
Douglas Gregorcb1c9c32011-10-14 15:55:40 +00002427 // Merge ns_returns_retained attribute.
2428 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2429 if (NewTypeInfo.getProducesResult()) {
2430 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2431 Diag(Old->getLocation(), diag::note_previous_declaration);
2432 return true;
2433 }
2434
2435 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2436 RequiresAdjustment = true;
2437 }
2438
John McCalle6a365d2010-12-19 02:44:49 +00002439 if (RequiresAdjustment) {
Eli Friedman130fcc82013-09-06 21:09:09 +00002440 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2441 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2442 New->setType(QualType(AdjustedType, 0));
John McCalle6a365d2010-12-19 02:44:49 +00002443 NewQType = Context.getCanonicalType(New->getType());
Eli Friedman130fcc82013-09-06 21:09:09 +00002444 NewType = cast<FunctionType>(NewQType);
Douglas Gregord2c64902010-06-18 21:30:25 +00002445 }
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002446
2447 // If this redeclaration makes the function inline, we may need to add it to
2448 // UndefinedButUsed.
2449 if (!Old->isInlined() && New->isInlined() &&
2450 !New->hasAttr<GNUInlineAttr>() &&
2451 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2452 Old->isUsed(false) &&
2453 !Old->isDefined() && !New->isThisDeclarationADefinition())
2454 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2455 SourceLocation()));
2456
2457 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2458 // about it.
2459 if (New->hasAttr<GNUInlineAttr>() &&
2460 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2461 UndefinedButUsed.erase(Old->getCanonicalDecl());
2462 }
Douglas Gregord2c64902010-06-18 21:30:25 +00002463
David Blaikie4e4d0842012-03-11 07:00:24 +00002464 if (getLangOpts().CPlusPlus) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002465 // (C++98 13.1p2):
2466 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00002467 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002468 // cannot be overloaded.
Richard Smith60e141e2013-05-04 07:00:32 +00002469
2470 // Go back to the type source info to compare the declared return types,
Richard Smith37e849a2013-08-14 20:16:31 +00002471 // per C++1y [dcl.type.auto]p13:
Richard Smith60e141e2013-05-04 07:00:32 +00002472 // Redeclarations or specializations of a function or function template
2473 // with a declared return type that uses a placeholder type shall also
2474 // use that placeholder, not a deduced type.
2475 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2476 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2477 : OldType)->getResultType();
2478 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2479 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2480 : NewType)->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002481 QualType ResQT;
Richard Smitha41c97a2013-09-20 01:15:31 +00002482 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2483 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2484 New->isLocalExternDecl())) {
Richard Smith60e141e2013-05-04 07:00:32 +00002485 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2486 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002487 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2488 if (ResQT.isNull()) {
Argyrios Kyrtzidis1de34dd2011-02-05 05:54:49 +00002489 if (New->isCXXClassMember() && New->isOutOfLine())
2490 Diag(New->getLocation(),
2491 diag::err_member_def_does_not_match_ret_type) << New;
2492 else
2493 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002494 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2495 return true;
2496 }
2497 else
2498 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002499 }
2500
Richard Smith60e141e2013-05-04 07:00:32 +00002501 QualType OldReturnType = OldType->getResultType();
2502 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2503 if (OldReturnType != NewReturnType) {
2504 // If this function has a deduced return type and has already been
2505 // defined, copy the deduced value from the old declaration.
2506 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2507 if (OldAT && OldAT->isDeduced()) {
Richard Smith37e849a2013-08-14 20:16:31 +00002508 New->setType(
2509 SubstAutoType(New->getType(),
2510 OldAT->isDependentType() ? Context.DependentTy
2511 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002512 NewQType = Context.getCanonicalType(
Richard Smith37e849a2013-08-14 20:16:31 +00002513 SubstAutoType(NewQType,
2514 OldAT->isDependentType() ? Context.DependentTy
2515 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002516 }
2517 }
2518
2519 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2520 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002521 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00002522 // Preserve triviality.
2523 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichete1e96a62011-05-14 19:17:07 +00002524
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002525 // MSVC allows explicit template specialization at class scope:
2526 // 2 CXMethodDecls referring to the same function will be injected.
2527 // We don't want a redeclartion error.
2528 bool IsClassScopeExplicitSpecialization =
2529 OldMethod->isFunctionTemplateSpecialization() &&
2530 NewMethod->isFunctionTemplateSpecialization();
John McCall3d043362010-04-13 07:45:41 +00002531 bool isFriend = NewMethod->getFriendObjectKind();
2532
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002533 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2534 !IsClassScopeExplicitSpecialization) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002535 // -- Member function declarations with the same name and the
2536 // same parameter types cannot be overloaded if any of them
2537 // is a static member function declaration.
Eli Friedmanfa0d3f82013-06-19 22:43:55 +00002538 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002539 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2540 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2541 return true;
2542 }
Richard Smith838925d2012-07-13 04:12:04 +00002543
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002544 // C++ [class.mem]p1:
2545 // [...] A member shall not be declared twice in the
2546 // member-specification, except that a nested class or member
2547 // class template can be declared and then later defined.
Richard Smith838925d2012-07-13 04:12:04 +00002548 if (ActiveTemplateInstantiations.empty()) {
2549 unsigned NewDiag;
2550 if (isa<CXXConstructorDecl>(OldMethod))
2551 NewDiag = diag::err_constructor_redeclared;
2552 else if (isa<CXXDestructorDecl>(NewMethod))
2553 NewDiag = diag::err_destructor_redeclared;
2554 else if (isa<CXXConversionDecl>(NewMethod))
2555 NewDiag = diag::err_conv_function_redeclared;
2556 else
2557 NewDiag = diag::err_member_redeclared;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002558
Richard Smith838925d2012-07-13 04:12:04 +00002559 Diag(New->getLocation(), NewDiag);
2560 } else {
2561 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2562 << New << New->getType();
2563 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00002564 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00002565
2566 // Complain if this is an explicit declaration of a special
2567 // member that was initially declared implicitly.
2568 //
2569 // As an exception, it's okay to befriend such methods in order
2570 // to permit the implicit constructor/destructor/operator calls.
2571 } else if (OldMethod->isImplicit()) {
2572 if (isFriend) {
2573 NewMethod->setImplicit();
2574 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002575 Diag(NewMethod->getLocation(),
2576 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002577 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002578 return true;
2579 }
Richard Smithf4fe8432012-06-08 01:30:54 +00002580 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Sean Hunt001cad92011-05-10 00:49:42 +00002581 Diag(NewMethod->getLocation(),
2582 diag::err_definition_of_explicitly_defaulted_member)
2583 << getSpecialMember(OldMethod);
2584 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002585 }
2586 }
2587
Richard Smithcd8ab512013-01-17 01:30:42 +00002588 // C++11 [dcl.attr.noreturn]p1:
2589 // The first declaration of a function shall specify the noreturn
2590 // attribute if any declaration of that function specifies the noreturn
2591 // attribute.
2592 if (New->hasAttr<CXX11NoReturnAttr>() &&
2593 !Old->hasAttr<CXX11NoReturnAttr>()) {
2594 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2595 diag::err_noreturn_missing_on_first_decl);
Rafael Espindolabc650912013-10-17 15:37:26 +00002596 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithcd8ab512013-01-17 01:30:42 +00002597 diag::note_noreturn_missing_first_decl);
2598 }
2599
Richard Smith3a2b7a12013-01-28 22:42:45 +00002600 // C++11 [dcl.attr.depend]p2:
2601 // The first declaration of a function shall specify the
2602 // carries_dependency attribute for its declarator-id if any declaration
2603 // of the function specifies the carries_dependency attribute.
2604 if (New->hasAttr<CarriesDependencyAttr>() &&
2605 !Old->hasAttr<CarriesDependencyAttr>()) {
2606 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2607 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindolabc650912013-10-17 15:37:26 +00002608 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002609 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2610 }
2611
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002612 // (C++98 8.3.5p3):
2613 // All declarations for a function shall agree exactly in both the
2614 // return type and the parameter-type-list.
John McCalle6a365d2010-12-19 02:44:49 +00002615 // We also want to respect all the extended bits except noreturn.
2616
2617 // noreturn should now match unless the old type info didn't have it.
2618 QualType OldQTypeForComparison = OldQType;
2619 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2620 assert(OldQType == QualType(OldType, 0));
2621 const FunctionType *OldTypeForComparison
2622 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2623 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2624 assert(OldQTypeForComparison.isCanonical());
2625 }
2626
Rafael Espindola950fee22013-02-14 01:18:37 +00002627 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokera8a2ebe2013-10-22 22:53:01 +00002628 // As a special case, retain the language linkage from previous
2629 // declarations of a friend function as an extension.
2630 //
2631 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2632 // and is useful because there's otherwise no way to specify language
2633 // linkage within class scope.
2634 //
2635 // Check cautiously as the friend object kind isn't yet complete.
2636 if (New->getFriendObjectKind() != Decl::FOK_None) {
2637 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2638 Diag(Old->getLocation(), PrevDiag);
2639 } else {
2640 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2641 Diag(Old->getLocation(), PrevDiag);
2642 return true;
2643 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00002644 }
2645
John McCalle6a365d2010-12-19 02:44:49 +00002646 if (OldQTypeForComparison == NewQType)
Richard Smithdd9459f2013-08-13 18:18:50 +00002647 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002648
Richard Smitha41c97a2013-09-20 01:15:31 +00002649 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2650 New->isLocalExternDecl()) {
2651 // It's OK if we couldn't merge types for a local function declaraton
2652 // if either the old or new type is dependent. We'll merge the types
2653 // when we instantiate the function.
2654 return false;
2655 }
2656
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002657 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00002658 }
Chris Lattner04421082008-04-08 04:40:51 +00002659
2660 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002661 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002662 if (!getLangOpts().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00002663 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00002664 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2665 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002666 const FunctionProtoType *OldProto = 0;
Richard Smithdd9459f2013-08-13 18:18:50 +00002667 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002668 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00002669 // The old declaration provided a function prototype, but the
2670 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00002671 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002672 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregor68719812009-02-16 18:20:44 +00002673 OldProto->arg_type_end());
2674 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002675 ParamTypes,
John McCalle23cf432010-12-14 08:05:40 +00002676 OldProto->getExtProtoInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00002677 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00002678 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00002679
2680 // Synthesize a parameter for each argument type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002681 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00002682 for (FunctionProtoType::arg_type_iterator
2683 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00002684 ParamEnd = OldProto->arg_type_end();
2685 ParamType != ParamEnd; ++ParamType) {
2686 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002687 SourceLocation(),
Douglas Gregor450da982009-02-16 20:58:07 +00002688 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002689 *ParamType, /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002690 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002691 0);
John McCallfb44de92011-05-01 22:35:37 +00002692 Param->setScopeInfo(0, Params.size());
Douglas Gregor450da982009-02-16 20:58:07 +00002693 Param->setImplicit();
2694 Params.push_back(Param);
2695 }
2696
David Blaikie4278c652011-09-21 18:16:56 +00002697 New->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00002698 }
Douglas Gregor68719812009-02-16 18:20:44 +00002699
Richard Smithdd9459f2013-08-13 18:18:50 +00002700 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattner04421082008-04-08 04:40:51 +00002701 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00002702
Douglas Gregorc8376562009-03-06 22:43:54 +00002703 // GNU C permits a K&R definition to follow a prototype declaration
2704 // if the declared types of the parameters in the K&R definition
2705 // match the types in the prototype declaration, even when the
2706 // promoted types of the parameters from the K&R definition differ
2707 // from the types in the prototype. GCC then keeps the types from
2708 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002709 //
2710 // If a variadic prototype is followed by a non-variadic K&R definition,
2711 // the K&R definition becomes variadic. This is sort of an edge case, but
2712 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2713 // C99 6.9.1p8.
David Blaikie4e4d0842012-03-11 07:00:24 +00002714 if (!getLangOpts().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002715 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00002716 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002717 Old->getNumParams() == New->getNumParams()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002718 SmallVector<QualType, 16> ArgTypes;
2719 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00002720 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00002721 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002722 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00002723 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002724
Douglas Gregorc8376562009-03-06 22:43:54 +00002725 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002726 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2727 NewProto->getResultType());
2728 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00002729 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002730 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002731 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2732 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00002733 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00002734 NewProto->getArgType(Idx))) {
2735 ArgTypes.push_back(NewParm->getType());
2736 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00002737 NewParm->getType(),
2738 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002739 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00002740 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2741 Warnings.push_back(Warn);
2742 ArgTypes.push_back(NewParm->getType());
2743 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002744 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00002745 }
2746
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002747 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002748 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2749 Diag(Warnings[Warn].NewParm->getLocation(),
2750 diag::ext_param_promoted_not_compatible_with_prototype)
2751 << Warnings[Warn].PromotedType
2752 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00002753 if (Warnings[Warn].OldParm->getLocation().isValid())
2754 Diag(Warnings[Warn].OldParm->getLocation(),
2755 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00002756 }
2757
Richard Smithdd9459f2013-08-13 18:18:50 +00002758 if (MergeTypeWithOld)
2759 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2760 OldProto->getExtProtoInfo()));
2761 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregorc8376562009-03-06 22:43:54 +00002762 }
2763
2764 // Fall through to diagnose conflicting types.
2765 }
2766
John McCall088831d2013-04-14 08:50:55 +00002767 // A function that has already been declared has been redeclared or
2768 // defined with a different type; show an appropriate diagnostic.
2769
2770 // If the previous declaration was an implicitly-generated builtin
2771 // declaration, then at the very least we should use a specialized note.
2772 unsigned BuiltinID;
2773 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2774 // If it's actually a library-defined builtin function like 'malloc'
2775 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002776 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002777 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2778 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2779 << Old << Old->getType();
John McCall088831d2013-04-14 08:50:55 +00002780
2781 // If this is a global redeclaration, just forget hereafter
2782 // about the "builtin-ness" of the function.
2783 //
2784 // Doing this for local extern declarations is problematic. If
2785 // the builtin declaration remains visible, a second invalid
2786 // local declaration will produce a hard error; if it doesn't
2787 // remain visible, a single bogus local redeclaration (which is
2788 // actually only a warning) could break all the downstream code.
Richard Smitha41c97a2013-09-20 01:15:31 +00002789 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCall088831d2013-04-14 08:50:55 +00002790 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2791
Douglas Gregor374e1562009-03-23 17:47:24 +00002792 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002793 }
Steve Naroff837618c2008-01-16 15:01:34 +00002794
Douglas Gregorcda9c672009-02-16 17:45:42 +00002795 PrevDiag = diag::note_previous_builtin_declaration;
2796 }
2797
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002798 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00002799 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00002800 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002801}
2802
Douglas Gregor04495c82009-02-24 01:23:02 +00002803/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00002804/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00002805///
2806/// This routine handles the merging of attributes and other
Alp Toker89673e02013-10-22 09:00:49 +00002807/// properties of function declarations from the old declaration to
Douglas Gregor04495c82009-02-24 01:23:02 +00002808/// the new declaration, once we know that New is in fact a
2809/// redeclaration of Old.
2810///
2811/// \returns false
James Molloy9cda03f2012-03-13 08:55:35 +00002812bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smithdd9459f2013-08-13 18:18:50 +00002813 Scope *S, bool MergeTypeWithOld) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002814 // Merge the attributes
Douglas Gregor27c6da22012-01-01 20:30:41 +00002815 mergeDeclAttributes(New, Old);
Douglas Gregor04495c82009-02-24 01:23:02 +00002816
Douglas Gregor04495c82009-02-24 01:23:02 +00002817 // Merge "pure" flag.
2818 if (Old->isPure())
2819 New->setPure();
2820
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002821 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00002822 if (Old->getMostRecentDecl()->isUsed(false))
2823 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002824
John McCalleca5d222011-03-02 04:00:57 +00002825 // Merge attributes from the parameters. These can mismatch with K&R
2826 // declarations.
2827 if (New->getNumParams() == Old->getNumParams())
2828 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2829 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002830 *this);
John McCalleca5d222011-03-02 04:00:57 +00002831
David Blaikie4e4d0842012-03-11 07:00:24 +00002832 if (getLangOpts().CPlusPlus)
James Molloy9cda03f2012-03-13 08:55:35 +00002833 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregor04495c82009-02-24 01:23:02 +00002834
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002835 // Merge the function types so the we get the composite types for the return
Richard Smithdd9459f2013-08-13 18:18:50 +00002836 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2837 // was visible.
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002838 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smithdd9459f2013-08-13 18:18:50 +00002839 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002840 New->setType(Merged);
2841
Douglas Gregor04495c82009-02-24 01:23:02 +00002842 return false;
2843}
2844
John McCallf85e1932011-06-15 23:02:42 +00002845
John McCalleca5d222011-03-02 04:00:57 +00002846void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002847 ObjCMethodDecl *oldMethod) {
John McCall6c2c2502011-07-22 02:45:48 +00002848
Fariborz Jahanian1ea67442012-06-05 21:14:46 +00002849 // Merge the attributes, including deprecated/unavailable
Ted Kremenekcb344392013-04-06 00:34:27 +00002850 AvailabilityMergeKind MergeKind =
2851 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2852 : AMK_Override;
2853 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCalleca5d222011-03-02 04:00:57 +00002854
2855 // Merge attributes from the parameters.
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002856 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2857 oe = oldMethod->param_end();
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002858 for (ObjCMethodDecl::param_iterator
John McCalleca5d222011-03-02 04:00:57 +00002859 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002860 ni != ne && oi != oe; ++ni, ++oi)
Richard Smith3a2b7a12013-01-28 22:42:45 +00002861 mergeParamDeclAttributes(*ni, *oi, *this);
John McCall6c2c2502011-07-22 02:45:48 +00002862
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002863 CheckObjCMethodOverride(newMethod, oldMethod);
John McCalleca5d222011-03-02 04:00:57 +00002864}
2865
Sebastian Redl60618fa2011-03-12 11:50:43 +00002866/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2867/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith34b41d92011-02-20 03:19:35 +00002868/// emitting diagnostics as appropriate.
2869///
2870/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002871/// to here in AddInitializerToDecl. We can't check them before the initializer
2872/// is attached.
Richard Smithdd9459f2013-08-13 18:18:50 +00002873void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2874 bool MergeTypeWithOld) {
Richard Smith34b41d92011-02-20 03:19:35 +00002875 if (New->isInvalidDecl() || Old->isInvalidDecl())
2876 return;
2877
2878 QualType MergedT;
David Blaikie4e4d0842012-03-11 07:00:24 +00002879 if (getLangOpts().CPlusPlus) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00002880 if (New->getType()->isUndeducedType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00002881 // We don't know what the new type is until the initializer is attached.
2882 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002883 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2884 // These could still be something that needs exception specs checked.
2885 return MergeVarDeclExceptionSpecs(New, Old);
2886 }
Richard Smith34b41d92011-02-20 03:19:35 +00002887 // C++ [basic.link]p10:
2888 // [...] the types specified by all declarations referring to a given
2889 // object or function shall be identical, except that declarations for an
2890 // array object can specify array types that differ by the presence or
2891 // absence of a major array bound (8.3.4).
2892 else if (Old->getType()->isIncompleteArrayType() &&
2893 New->getType()->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002894 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2895 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2896 if (Context.hasSameType(OldArray->getElementType(),
2897 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002898 MergedT = New->getType();
2899 } else if (Old->getType()->isArrayType() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00002900 New->getType()->isIncompleteArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002901 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2902 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2903 if (Context.hasSameType(OldArray->getElementType(),
2904 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002905 MergedT = Old->getType();
Richard Smitha41c97a2013-09-20 01:15:31 +00002906 } else if (New->getType()->isObjCObjectPointerType() &&
2907 Old->getType()->isObjCObjectPointerType()) {
2908 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2909 Old->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00002910 }
2911 } else {
Richard Smitha41c97a2013-09-20 01:15:31 +00002912 // C 6.2.7p2:
2913 // All declarations that refer to the same object or function shall have
2914 // compatible type.
Richard Smith34b41d92011-02-20 03:19:35 +00002915 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2916 }
2917 if (MergedT.isNull()) {
Richard Smithdd9459f2013-08-13 18:18:50 +00002918 // It's OK if we couldn't merge types if either type is dependent, for a
2919 // block-scope variable. In other cases (static data members of class
2920 // templates, variable templates, ...), we require the types to be
2921 // equivalent.
2922 // FIXME: The C++ standard doesn't say anything about this.
2923 if ((New->getType()->isDependentType() ||
2924 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2925 // If the old type was dependent, we can't merge with it, so the new type
2926 // becomes dependent for now. We'll reproduce the original type when we
2927 // instantiate the TypeSourceInfo for the variable.
2928 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2929 New->setType(Context.DependentTy);
2930 return;
2931 }
2932
2933 // FIXME: Even if this merging succeeds, some other non-visible declaration
2934 // of this variable might have an incompatible type. For instance:
2935 //
2936 // extern int arr[];
2937 // void f() { extern int arr[2]; }
2938 // void g() { extern int arr[3]; }
2939 //
2940 // Neither C nor C++ requires a diagnostic for this, but we should still try
2941 // to diagnose it.
Richard Smith34b41d92011-02-20 03:19:35 +00002942 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikiea405b252012-09-20 18:38:57 +00002943 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00002944 Diag(Old->getLocation(), diag::note_previous_definition);
2945 return New->setInvalidDecl();
2946 }
John McCall5b8740f2013-04-01 18:34:28 +00002947
2948 // Don't actually update the type on the new declaration if the old
Richard Smith99a72382013-09-03 21:00:58 +00002949 // declaration was an extern declaration in a different scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00002950 if (MergeTypeWithOld)
John McCall5b8740f2013-04-01 18:34:28 +00002951 New->setType(MergedT);
Richard Smith34b41d92011-02-20 03:19:35 +00002952}
2953
Richard Smith99a72382013-09-03 21:00:58 +00002954static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2955 LookupResult &Previous) {
2956 // C11 6.2.7p4:
2957 // For an identifier with internal or external linkage declared
2958 // in a scope in which a prior declaration of that identifier is
2959 // visible, if the prior declaration specifies internal or
2960 // external linkage, the type of the identifier at the later
2961 // declaration becomes the composite type.
2962 //
2963 // If the variable isn't visible, we do not merge with its type.
2964 if (Previous.isShadowed())
2965 return false;
2966
2967 if (S.getLangOpts().CPlusPlus) {
2968 // C++11 [dcl.array]p3:
2969 // If there is a preceding declaration of the entity in the same
2970 // scope in which the bound was specified, an omitted array bound
2971 // is taken to be the same as in that earlier declaration.
2972 return NewVD->isPreviousDeclInSameBlockScope() ||
2973 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2974 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2975 } else {
2976 // If the old declaration was function-local, don't merge with its
2977 // type unless we're in the same function.
2978 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2979 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2980 }
2981}
2982
Reid Spencer5f016e22007-07-11 17:01:13 +00002983/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2984/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2985/// situation, merging decls or emitting diagnostics as appropriate.
2986///
Mike Stump1eb44332009-09-09 15:08:12 +00002987/// Tentative definition rules (C99 6.9.2p2) are checked by
2988/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002989/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00002990///
Richard Smith99a72382013-09-03 21:00:58 +00002991void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall68263142009-11-18 22:49:29 +00002992 // If the new decl is already invalid, don't do any other checking.
2993 if (New->isInvalidDecl())
2994 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Larisse Voufo4a919892013-08-14 03:09:19 +00002996 // Verify the old decl was also a variable or variable template.
John McCall68263142009-11-18 22:49:29 +00002997 VarDecl *Old = 0;
Larisse Voufo4a919892013-08-14 03:09:19 +00002998 if (Previous.isSingleResult() &&
2999 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo567f9172013-08-22 00:59:14 +00003000 if (New->getDescribedVarTemplate())
Larisse Voufo4a919892013-08-14 03:09:19 +00003001 Old = Old->getDescribedVarTemplate() ? Old : 0;
3002 else
3003 Old = Old->getDescribedVarTemplate() ? 0 : Old;
3004 }
3005 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003006 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00003007 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00003008 Diag(Previous.getRepresentativeDecl()->getLocation(),
3009 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003010 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003011 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003012
Rafael Espindola90cc3902013-04-15 12:49:13 +00003013 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3014 return;
3015
Douglas Gregor7f6ff022010-08-30 14:32:14 +00003016 // C++ [class.mem]p1:
3017 // A member shall not be declared twice in the member-specification [...]
3018 //
3019 // Here, we need only consider static data members.
3020 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3021 Diag(New->getLocation(), diag::err_duplicate_member)
3022 << New->getIdentifier();
3023 Diag(Old->getLocation(), diag::note_previous_declaration);
3024 New->setInvalidDecl();
3025 }
3026
Douglas Gregor27c6da22012-01-01 20:30:41 +00003027 mergeDeclAttributes(New, Old);
David Blaikied662a792011-10-19 22:56:21 +00003028 // Warn if an already-declared variable is made a weak_import in a subsequent
3029 // declaration
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00003030 if (New->getAttr<WeakImportAttr>() &&
3031 Old->getStorageClass() == SC_None &&
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003032 !Old->getAttr<WeakImportAttr>()) {
3033 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3034 Diag(Old->getLocation(), diag::note_previous_definition);
3035 // Remove weak_import attribute on new declaration.
Fariborz Jahanianc3ca14d2011-06-23 17:50:10 +00003036 New->dropAttr<WeakImportAttr>();
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003037 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003038
Richard Smith34b41d92011-02-20 03:19:35 +00003039 // Merge the types.
Richard Smith99a72382013-09-03 21:00:58 +00003040 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3041
Richard Smith34b41d92011-02-20 03:19:35 +00003042 if (New->isInvalidDecl())
3043 return;
Douglas Gregor656de632009-03-11 23:52:16 +00003044
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003045 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCalld931b082010-08-26 03:08:43 +00003046 if (New->getStorageClass() == SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003047 !New->isStaticDataMember() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00003048 Old->hasExternalFormalLinkage()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003049 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003050 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003051 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003052 }
Mike Stump1eb44332009-09-09 15:08:12 +00003053 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003054 // For an identifier declared with the storage-class specifier
3055 // extern in a scope in which a prior declaration of that
3056 // identifier is visible,23) if the prior declaration specifies
3057 // internal or external linkage, the linkage of the identifier at
3058 // the later declaration is the same as the linkage specified at
3059 // the prior declaration. If no prior declaration is visible, or
3060 // if the prior declaration specifies no linkage, then the
3061 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00003062 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003063 /* Okay */;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003064 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003065 !New->isStaticDataMember() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003066 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003067 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003068 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003069 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003070 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003071
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003072 // Check if extern is followed by non-extern and vice-versa.
3073 if (New->hasExternalStorage() &&
3074 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3075 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3076 Diag(Old->getLocation(), diag::note_previous_definition);
3077 return New->setInvalidDecl();
3078 }
Rafael Espindola80a86892013-04-04 02:47:57 +00003079 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3080 !New->hasExternalStorage()) {
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003081 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3082 Diag(Old->getLocation(), diag::note_previous_definition);
3083 return New->setInvalidDecl();
3084 }
3085
Steve Naroff094cefb2008-09-17 14:05:40 +00003086 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003088 // FIXME: The test for external storage here seems wrong? We still
3089 // need to check for mismatches.
3090 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00003091 // Don't complain about out-of-line definitions of static members.
3092 !(Old->getLexicalDeclContext()->isRecord() &&
3093 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00003094 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003095 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003096 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003097 }
Douglas Gregor275a3692009-03-10 23:43:53 +00003098
Richard Smith38afbc72013-04-13 02:43:54 +00003099 if (New->getTLSKind() != Old->getTLSKind()) {
3100 if (!Old->getTLSKind()) {
3101 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3102 Diag(Old->getLocation(), diag::note_previous_declaration);
3103 } else if (!New->getTLSKind()) {
3104 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3105 Diag(Old->getLocation(), diag::note_previous_declaration);
3106 } else {
3107 // Do not allow redeclaration to change the variable between requiring
3108 // static and dynamic initialization.
3109 // FIXME: GCC allows this, but uses the TLS keyword on the first
3110 // declaration to determine the kind. Do we need to be compatible here?
3111 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3112 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3113 Diag(Old->getLocation(), diag::note_previous_declaration);
3114 }
Eli Friedman63054b32009-04-19 20:27:55 +00003115 }
3116
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003117 // C++ doesn't have tentative definitions, so go right ahead and check here.
3118 const VarDecl *Def;
David Blaikie4e4d0842012-03-11 07:00:24 +00003119 if (getLangOpts().CPlusPlus &&
Sebastian Redl6c048a92010-02-03 02:08:48 +00003120 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003121 (Def = Old->getDefinition())) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003122 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003123 Diag(Def->getLocation(), diag::note_previous_definition);
3124 New->setInvalidDecl();
3125 return;
3126 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003127
Rafael Espindola950fee22013-02-14 01:18:37 +00003128 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003129 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3130 Diag(Old->getLocation(), diag::note_previous_definition);
3131 New->setInvalidDecl();
3132 return;
3133 }
3134
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003135 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00003136 if (Old->getMostRecentDecl()->isUsed(false))
3137 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003138
Douglas Gregor275a3692009-03-10 23:43:53 +00003139 // Keep a chain of previous declarations.
Rafael Espindolabc650912013-10-17 15:37:26 +00003140 New->setPreviousDecl(Old);
John McCall46460a62010-01-20 21:53:11 +00003141
3142 // Inherit access appropriately.
3143 New->setAccess(Old->getAccess());
Larisse Voufo567f9172013-08-22 00:59:14 +00003144
3145 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3146 if (New->isStaticDataMember() && New->isOutOfLine())
3147 VTD->setAccess(New->getAccess());
3148 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003149}
3150
3151/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3152/// no declarator (e.g. "struct foo;") is parsed.
John McCalld226f652010-08-21 09:40:31 +00003153Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallac4df242011-03-22 23:00:04 +00003154 DeclSpec &DS) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00003155 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth0f4be742011-05-03 18:35:10 +00003156}
3157
Eli Friedman5e867c82013-07-10 00:30:46 +00003158static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00003159 if (!S.Context.getLangOpts().CPlusPlus)
3160 return;
3161
Eli Friedman5e867c82013-07-10 00:30:46 +00003162 if (isa<CXXRecordDecl>(Tag->getParent())) {
3163 // If this tag is the direct child of a class, number it if
3164 // it is anonymous.
3165 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3166 return;
3167 MangleNumberingContext &MCtx =
3168 S.Context.getManglingNumberContext(Tag->getParent());
3169 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3170 return;
3171 }
3172
3173 // If this tag isn't a direct child of a class, number it if it is local.
3174 Decl *ManglingContextDecl;
3175 if (MangleNumberingContext *MCtx =
3176 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3177 ManglingContextDecl)) {
3178 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3179 }
3180}
3181
Chandler Carruth0f4be742011-05-03 18:35:10 +00003182/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithc7f81162013-03-18 22:52:47 +00003183/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth0f4be742011-05-03 18:35:10 +00003184/// parameters to cope with template friend declarations.
3185Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3186 DeclSpec &DS,
Richard Smithc7f81162013-03-18 22:52:47 +00003187 MultiTemplateParamsArg TemplateParams,
3188 bool IsExplicitInstantiation) {
John McCalle3af0232009-10-07 23:34:25 +00003189 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003190 TagDecl *Tag = 0;
3191 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3192 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003193 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003194 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003195 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallb3d87482010-08-24 05:47:05 +00003196 TagD = DS.getRepAsDecl();
John McCalle3af0232009-10-07 23:34:25 +00003197
3198 if (!TagD) // We probably had an error
John McCalld226f652010-08-21 09:40:31 +00003199 return 0;
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003200
John McCall67d1a672009-08-06 02:15:43 +00003201 // Note that the above type specs guarantee that the
3202 // type rep is a Decl, whereas in many of the others
3203 // it's a Type.
Peter Collingbourne0661bd0c2011-10-23 17:07:16 +00003204 if (isa<TagDecl>(TagD))
3205 Tag = cast<TagDecl>(TagD);
3206 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3207 Tag = CTD->getTemplatedDecl();
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003208 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003209
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003210 if (Tag) {
Eli Friedman5e867c82013-07-10 00:30:46 +00003211 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003212 Tag->setFreeStanding();
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003213 if (Tag->isInvalidDecl())
3214 return Tag;
3215 }
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003216
Nuno Lopes0a8bab02009-12-17 11:35:26 +00003217 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3218 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3219 // or incomplete types shall not be restrict-qualified."
3220 if (TypeQuals & DeclSpec::TQ_restrict)
3221 Diag(DS.getRestrictSpecLoc(),
3222 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3223 << DS.getSourceRange();
3224 }
3225
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003226 if (DS.isConstexprSpecified()) {
3227 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3228 // and definitions of functions and variables.
3229 if (Tag)
3230 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3231 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3232 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003233 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3234 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003235 else
3236 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3237 // Don't emit warnings after this error.
3238 return TagD;
3239 }
3240
Richard Smithc7f81162013-03-18 22:52:47 +00003241 DiagnoseFunctionSpecifiers(DS);
3242
Douglas Gregord85bea22009-09-26 06:47:28 +00003243 if (DS.isFriendSpecified()) {
John McCall9a34edb2010-10-19 01:40:49 +00003244 // If we're dealing with a decl but not a TagDecl, assume that
3245 // whatever routines created it handled the friendship aspect.
3246 if (TagD && !Tag)
John McCalld226f652010-08-21 09:40:31 +00003247 return 0;
Chandler Carruth0f4be742011-05-03 18:35:10 +00003248 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregord85bea22009-09-26 06:47:28 +00003249 }
John McCallac4df242011-03-22 23:00:04 +00003250
Richard Smithc7f81162013-03-18 22:52:47 +00003251 CXXScopeSpec &SS = DS.getTypeSpecScope();
3252 bool IsExplicitSpecialization =
3253 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3254 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3255 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3256 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3257 // nested-name-specifier unless it is an explicit instantiation
3258 // or an explicit specialization.
3259 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3260 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3261 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3262 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3263 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3264 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3265 << SS.getRange();
3266 return 0;
3267 }
3268
3269 // Track whether this decl-specifier declares anything.
3270 bool DeclaresAnything = true;
3271
3272 // Handle anonymous struct definitions.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003273 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall5e1cdac2011-10-07 06:10:15 +00003274 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00003275 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003276 if (getLangOpts().CPlusPlus ||
Douglas Gregora71c1292009-03-06 23:06:59 +00003277 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00003278 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00003279
Richard Smithc7f81162013-03-18 22:52:47 +00003280 DeclaresAnything = false;
Douglas Gregora71c1292009-03-06 23:06:59 +00003281 }
Francois Pichet8e161ed2010-11-23 06:07:27 +00003282 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003283
Richard Smithc7f81162013-03-18 22:52:47 +00003284 // Check for Microsoft C extension: anonymous struct member.
David Blaikie4e4d0842012-03-11 07:00:24 +00003285 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet8e161ed2010-11-23 06:07:27 +00003286 CurContext->isRecord() &&
3287 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3288 // Handle 2 kinds of anonymous struct:
3289 // struct STRUCT;
3290 // and
3291 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3292 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCall5e1cdac2011-10-07 06:10:15 +00003293 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet8e161ed2010-11-23 06:07:27 +00003294 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3295 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003296 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet8e161ed2010-11-23 06:07:27 +00003297 << DS.getSourceRange();
3298 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3299 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003300 }
Richard Smithc7f81162013-03-18 22:52:47 +00003301
3302 // Skip all the checks below if we have a type error.
3303 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3304 (TagD && TagD->isInvalidDecl()))
3305 return TagD;
3306
3307 if (getLangOpts().CPlusPlus &&
Douglas Gregora131d0f2010-07-13 06:24:26 +00003308 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3309 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3310 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithc7f81162013-03-18 22:52:47 +00003311 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3312 DeclaresAnything = false;
John McCallac4df242011-03-22 23:00:04 +00003313
John McCallac4df242011-03-22 23:00:04 +00003314 if (!DS.isMissingDeclaratorOk()) {
Richard Smithc7f81162013-03-18 22:52:47 +00003315 // Customize diagnostic for a typedef missing a name.
3316 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003317 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregora0ebd602010-07-16 15:40:40 +00003318 << DS.getSourceRange();
Richard Smithc7f81162013-03-18 22:52:47 +00003319 else
3320 DeclaresAnything = false;
Sebastian Redla4ed0d82008-12-28 15:28:59 +00003321 }
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Richard Smithc7f81162013-03-18 22:52:47 +00003323 if (DS.isModulePrivateSpecified() &&
Douglas Gregore3895852011-09-12 18:37:38 +00003324 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3325 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3326 << Tag->getTagKind()
3327 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3328
Richard Smithc7f81162013-03-18 22:52:47 +00003329 ActOnDocumentableDecl(TagD);
3330
3331 // C 6.7/2:
3332 // A declaration [...] shall declare at least a declarator [...], a tag,
3333 // or the members of an enumeration.
3334 // C++ [dcl.dcl]p3:
3335 // [If there are no declarators], and except for the declaration of an
3336 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3337 // names into the program, or shall redeclare a name introduced by a
3338 // previous declaration.
3339 if (!DeclaresAnything) {
3340 // In C, we allow this as a (popular) extension / bug. Don't bother
3341 // producing further diagnostics for redundant qualifiers after this.
3342 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3343 return TagD;
3344 }
3345
3346 // C++ [dcl.stc]p1:
3347 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3348 // init-declarator-list of the declaration shall not be empty.
3349 // C++ [dcl.fct.spec]p1:
3350 // If a cv-qualifier appears in a decl-specifier-seq, the
3351 // init-declarator-list of the declaration shall not be empty.
3352 //
3353 // Spurious qualifiers here appear to be valid in C.
3354 unsigned DiagID = diag::warn_standalone_specifier;
3355 if (getLangOpts().CPlusPlus)
3356 DiagID = diag::ext_standalone_specifier;
3357
3358 // Note that a linkage-specification sets a storage class, but
3359 // 'extern "C" struct foo;' is actually valid and not theoretically
3360 // useless.
3361 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3362 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3363 Diag(DS.getStorageClassSpecLoc(), DiagID)
3364 << DeclSpec::getSpecifierName(SCS);
3365
Richard Smithec642442013-04-12 22:46:28 +00003366 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3367 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3368 << DeclSpec::getSpecifierName(TSCS);
Richard Smithc7f81162013-03-18 22:52:47 +00003369 if (DS.getTypeQualifiers()) {
3370 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3371 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3372 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3373 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3374 // Restrict is covered above.
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003375 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3376 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithc7f81162013-03-18 22:52:47 +00003377 }
3378
Eli Friedmanfc038e92011-12-17 00:36:09 +00003379 // Warn about ignored type attributes, for example:
3380 // __attribute__((aligned)) struct A;
Bill Wendlingad017fa2012-12-20 19:22:21 +00003381 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmanfc038e92011-12-17 00:36:09 +00003382 if (!DS.getAttributes().empty()) {
3383 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3384 if (TypeSpecType == DeclSpec::TST_class ||
3385 TypeSpecType == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003386 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmanfc038e92011-12-17 00:36:09 +00003387 TypeSpecType == DeclSpec::TST_union ||
3388 TypeSpecType == DeclSpec::TST_enum) {
3389 AttributeList* attrs = DS.getAttributes().getList();
3390 while (attrs) {
Michael Han45bed132012-10-04 16:42:52 +00003391 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmanfc038e92011-12-17 00:36:09 +00003392 << attrs->getName()
3393 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3394 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003395 TypeSpecType == DeclSpec::TST_union ? 2 :
3396 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmanfc038e92011-12-17 00:36:09 +00003397 attrs = attrs->getNext();
3398 }
3399 }
3400 }
John McCallac4df242011-03-22 23:00:04 +00003401
John McCalld226f652010-08-21 09:40:31 +00003402 return TagD;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003403}
3404
John McCall1d7c5282009-12-18 10:40:03 +00003405/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00003406/// check if there's an existing declaration that can't be overloaded.
3407///
3408/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00003409static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3410 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00003411 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00003412 DeclarationName Name,
3413 SourceLocation NameLoc,
3414 unsigned diagnostic) {
3415 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3416 Sema::ForRedeclaration);
3417 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00003418
John McCall1d7c5282009-12-18 10:40:03 +00003419 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00003420 return false;
3421
3422 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00003423 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidis2b642392010-09-23 14:26:01 +00003424 assert(PrevDecl && "Expected a non-null Decl");
3425
3426 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3427 return false;
John McCall68263142009-11-18 22:49:29 +00003428
John McCall1d7c5282009-12-18 10:40:03 +00003429 SemaRef.Diag(NameLoc, diagnostic) << Name;
3430 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00003431
3432 return true;
3433}
3434
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003435/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3436/// anonymous struct or union AnonRecord into the owning context Owner
3437/// and scope S. This routine will be invoked just after we realize
3438/// that an unnamed union or struct is actually an anonymous union or
3439/// struct, e.g.,
3440///
3441/// @code
3442/// union {
3443/// int i;
3444/// float f;
3445/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3446/// // f into the surrounding scope.x
3447/// @endcode
3448///
3449/// This routine is recursive, injecting the names of nested anonymous
3450/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00003451static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper6b9240e2013-07-05 19:34:19 +00003452 DeclContext *Owner,
3453 RecordDecl *AnonRecord,
3454 AccessSpecifier AS,
3455 SmallVectorImpl<NamedDecl *> &Chaining,
3456 bool MSAnonStruct) {
John McCall68263142009-11-18 22:49:29 +00003457 unsigned diagKind
3458 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3459 : diag::err_anonymous_struct_member_redecl;
3460
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003461 bool Invalid = false;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003462
3463 // Look every FieldDecl and IndirectFieldDecl with a name.
3464 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3465 DEnd = AnonRecord->decls_end();
3466 D != DEnd; ++D) {
3467 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3468 cast<NamedDecl>(*D)->getDeclName()) {
3469 ValueDecl *VD = cast<ValueDecl>(*D);
3470 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3471 VD->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003472 // C++ [class.union]p2:
3473 // The names of the members of an anonymous union shall be
3474 // distinct from the names of any other entity in the
3475 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003476 Invalid = true;
3477 } else {
3478 // C++ [class.union]p2:
3479 // For the purpose of name lookup, after the anonymous union
3480 // definition, the members of the anonymous union are
3481 // considered to have been defined in the scope in which the
3482 // anonymous union is declared.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003483 unsigned OldChainingSize = Chaining.size();
3484 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3485 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3486 PE = IF->chain_end(); PI != PE; ++PI)
3487 Chaining.push_back(*PI);
3488 else
3489 Chaining.push_back(VD);
3490
Francois Pichet87c2e122010-11-21 06:08:52 +00003491 assert(Chaining.size() >= 2);
3492 NamedDecl **NamedChain =
3493 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3494 for (unsigned i = 0; i < Chaining.size(); i++)
3495 NamedChain[i] = Chaining[i];
3496
3497 IndirectFieldDecl* IndirectField =
Francois Pichet8e161ed2010-11-23 06:07:27 +00003498 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3499 VD->getIdentifier(), VD->getType(),
Francois Pichet87c2e122010-11-21 06:08:52 +00003500 NamedChain, Chaining.size());
3501
3502 IndirectField->setAccess(AS);
3503 IndirectField->setImplicit();
3504 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallaec03712010-05-21 20:45:30 +00003505
3506 // That includes picking up the appropriate access specifier.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003507 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet87c2e122010-11-21 06:08:52 +00003508
Francois Pichet8e161ed2010-11-23 06:07:27 +00003509 Chaining.resize(OldChainingSize);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003510 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003511 }
3512 }
3513
3514 return Invalid;
3515}
3516
Douglas Gregor16573fa2010-04-19 22:54:31 +00003517/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3518/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCalld931b082010-08-26 03:08:43 +00003519/// illegal input values are mapped to SC_None.
3520static StorageClass
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003521StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3522 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3523 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3524 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregor16573fa2010-04-19 22:54:31 +00003525 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00003526 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003527 case DeclSpec::SCS_extern:
3528 if (DS.isExternInLinkageSpec())
3529 return SC_None;
3530 return SC_Extern;
John McCalld931b082010-08-26 03:08:43 +00003531 case DeclSpec::SCS_static: return SC_Static;
3532 case DeclSpec::SCS_auto: return SC_Auto;
3533 case DeclSpec::SCS_register: return SC_Register;
3534 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003535 // Illegal SCSs map to None: error reporting is up to the caller.
3536 case DeclSpec::SCS_mutable: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00003537 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003538 }
3539 llvm_unreachable("unknown storage class specifier");
3540}
3541
Francois Pichet8e161ed2010-11-23 06:07:27 +00003542/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003543/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgacbabf12012-02-03 15:47:04 +00003544/// (C++ [class.union]) and a C11 feature; anonymous structures
3545/// are a C11 feature and GNU C++ extension.
John McCalld226f652010-08-21 09:40:31 +00003546Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3547 AccessSpecifier AS,
3548 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003549 DeclContext *Owner = Record->getDeclContext();
3550
3551 // Diagnose whether this anonymous struct/union is an extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00003552 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003553 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikie4e4d0842012-03-11 07:00:24 +00003554 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003555 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikie4e4d0842012-03-11 07:00:24 +00003556 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003557 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003559 // C and C++ require different kinds of checks for anonymous
3560 // structs/unions.
3561 bool Invalid = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00003562 if (getLangOpts().CPlusPlus) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003563 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00003564 unsigned DiagID;
David Blaikie2b79c322011-10-19 22:43:29 +00003565 if (Record->isUnion()) {
3566 // C++ [class.union]p6:
3567 // Anonymous unions declared in a named namespace or in the
3568 // global namespace shall be declared static.
3569 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3570 (isa<TranslationUnitDecl>(Owner) ||
3571 (isa<NamespaceDecl>(Owner) &&
3572 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie82c8ca12011-10-20 02:49:08 +00003573 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3574 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie2b79c322011-10-19 22:43:29 +00003575
3576 // Recover by adding 'static'.
3577 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3578 PrevSpec, DiagID);
3579 }
3580 // C++ [class.union]p6:
3581 // A storage class is not allowed in a declaration of an
3582 // anonymous union in a class scope.
3583 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3584 isa<RecordDecl>(Owner)) {
3585 Diag(DS.getStorageClassSpecLoc(),
David Blaikief6f876c2011-10-20 02:10:55 +00003586 diag::err_anonymous_union_with_storage_spec)
3587 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie2b79c322011-10-19 22:43:29 +00003588
3589 // Recover by removing the storage specifier.
David Blaikied662a792011-10-19 22:56:21 +00003590 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3591 SourceLocation(),
David Blaikie2b79c322011-10-19 22:43:29 +00003592 PrevSpec, DiagID);
3593 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003594 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003595
Douglas Gregor7604f642011-05-09 23:05:33 +00003596 // Ignore const/volatile/restrict qualifiers.
3597 if (DS.getTypeQualifiers()) {
3598 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3599 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003600 << Record->isUnion() << "const"
Douglas Gregor7604f642011-05-09 23:05:33 +00003601 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3602 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003603 Diag(DS.getVolatileSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003604 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003605 << Record->isUnion() << "volatile"
Douglas Gregor7604f642011-05-09 23:05:33 +00003606 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3607 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003608 Diag(DS.getRestrictSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003609 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003610 << Record->isUnion() << "restrict"
Douglas Gregor7604f642011-05-09 23:05:33 +00003611 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003612 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3613 Diag(DS.getAtomicSpecLoc(),
3614 diag::ext_anonymous_struct_union_qualified)
3615 << Record->isUnion() << "_Atomic"
3616 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor7604f642011-05-09 23:05:33 +00003617
3618 DS.ClearTypeQualifiers();
3619 }
3620
Mike Stump1eb44332009-09-09 15:08:12 +00003621 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003622 // The member-specification of an anonymous union shall only
3623 // define non-static data members. [Note: nested types and
3624 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003625 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3626 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003627 Mem != MemEnd; ++Mem) {
3628 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3629 // C++ [class.union]p3:
3630 // An anonymous union shall not have private or protected
3631 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00003632 assert(FD->getAccess() != AS_none);
3633 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003634 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3635 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3636 Invalid = true;
3637 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003638
Sean Huntcf34e752011-05-16 22:41:40 +00003639 // C++ [class.union]p1
3640 // An object of a class with a non-trivial constructor, a non-trivial
3641 // copy constructor, a non-trivial destructor, or a non-trivial copy
3642 // assignment operator cannot be a member of a union, nor can an
3643 // array of such objects.
Richard Smithe7d7c392011-10-19 20:41:51 +00003644 if (CheckNontrivialField(FD))
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003645 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003646 } else if ((*Mem)->isImplicit()) {
3647 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00003648 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3649 // This is a type that showed up in an
3650 // elaborated-type-specifier inside the anonymous struct or
3651 // union, but which actually declares a type outside of the
3652 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003653 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3654 if (!MemRecord->isAnonymousStructOrUnion() &&
3655 MemRecord->getDeclName()) {
Francois Pichet538e0d02010-09-08 11:32:25 +00003656 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003657 if (getLangOpts().MicrosoftExt)
Francois Pichet538e0d02010-09-08 11:32:25 +00003658 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3659 << (int)Record->isUnion();
3660 else {
3661 // This is a nested type declaration.
3662 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3663 << (int)Record->isUnion();
3664 Invalid = true;
3665 }
Richard Smithc5f7d6a2013-01-28 00:54:05 +00003666 } else {
3667 // This is an anonymous type definition within another anonymous type.
3668 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3669 // not part of standard C++.
3670 Diag(MemRecord->getLocation(),
Richard Smithf2705192013-01-31 03:11:12 +00003671 diag::ext_anonymous_record_with_anonymous_type)
3672 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003673 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00003674 } else if (isa<AccessSpecDecl>(*Mem)) {
3675 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003676 } else {
3677 // We have something that isn't a non-static data
3678 // member. Complain about it.
3679 unsigned DK = diag::err_anonymous_record_bad_member;
3680 if (isa<TypeDecl>(*Mem))
3681 DK = diag::err_anonymous_record_with_type;
3682 else if (isa<FunctionDecl>(*Mem))
3683 DK = diag::err_anonymous_record_with_function;
3684 else if (isa<VarDecl>(*Mem))
3685 DK = diag::err_anonymous_record_with_static;
Francois Pichet538e0d02010-09-08 11:32:25 +00003686
3687 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003688 if (getLangOpts().MicrosoftExt &&
Francois Pichet538e0d02010-09-08 11:32:25 +00003689 DK == diag::err_anonymous_record_with_type)
3690 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003691 << (int)Record->isUnion();
Francois Pichet538e0d02010-09-08 11:32:25 +00003692 else {
3693 Diag((*Mem)->getLocation(), DK)
3694 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003695 Invalid = true;
Francois Pichet538e0d02010-09-08 11:32:25 +00003696 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003697 }
3698 }
Mike Stump1eb44332009-09-09 15:08:12 +00003699 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003700
3701 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003702 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikie4e4d0842012-03-11 07:00:24 +00003703 << (int)getLangOpts().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003704 Invalid = true;
3705 }
3706
John McCalleb692e02009-10-22 23:31:08 +00003707 // Mock up a declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003708 Declarator Dc(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00003709 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00003710 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00003711
Mike Stump1eb44332009-09-09 15:08:12 +00003712 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003713 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003714 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003715 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003716 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003717 Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003718 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003719 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00003720 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003721 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003722 /*InitStyle=*/ICIS_NoInit);
John McCallaec03712010-05-21 20:45:30 +00003723 Anon->setAccess(AS);
David Blaikie4e4d0842012-03-11 07:00:24 +00003724 if (getLangOpts().CPlusPlus)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003725 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003726 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00003727 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003728 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003729 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003730 // mutable can only appear on non-static class members, so it's always
3731 // an error here
3732 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3733 Invalid = true;
John McCalld931b082010-08-26 03:08:43 +00003734 SC = SC_None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003735 }
3736
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003737 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003738 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003739 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003740 Context.getTypeDeclType(Record),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003741 TInfo, SC);
Richard Smith16ee8192011-09-18 00:06:34 +00003742
3743 // Default-initialize the implicit variable. This initialization will be
3744 // trivial in almost all cases, except if a union member has an in-class
3745 // initializer:
3746 // union { int n = 0; };
3747 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003748 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003749 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003750
3751 // Add the anonymous struct/union object to the current
3752 // context. We'll be referencing this object when we refer to one of
3753 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003754 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00003755
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003756 // Inject the members of the anonymous struct/union into the owning
3757 // context and into the identifier resolver chain for name lookup
3758 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003759 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet87c2e122010-11-21 06:08:52 +00003760 Chain.push_back(Anon);
3761
Francois Pichet8e161ed2010-11-23 06:07:27 +00003762 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3763 Chain, false))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003764 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003765
3766 // Mark this as an anonymous struct/union type. Note that we do not
3767 // do this until after we have already checked and injected the
3768 // members of this anonymous struct/union type, because otherwise
3769 // the members could be injected twice: once by DeclContext when it
3770 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00003771 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003772 Record->setAnonymousStructOrUnion(true);
3773
3774 if (Invalid)
3775 Anon->setInvalidDecl();
3776
John McCalld226f652010-08-21 09:40:31 +00003777 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003778}
3779
Francois Pichet8e161ed2010-11-23 06:07:27 +00003780/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3781/// Microsoft C anonymous structure.
3782/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3783/// Example:
3784///
3785/// struct A { int a; };
3786/// struct B { struct A; int b; };
3787///
3788/// void foo() {
3789/// B var;
3790/// var.a = 3;
3791/// }
3792///
3793Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3794 RecordDecl *Record) {
3795
3796 // If there is no Record, get the record via the typedef.
3797 if (!Record)
3798 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3799
3800 // Mock up a declarator.
3801 Declarator Dc(DS, Declarator::TypeNameContext);
3802 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3803 assert(TInfo && "couldn't build declarator info for anonymous struct");
3804
3805 // Create a declaration for this anonymous struct.
3806 NamedDecl* Anon = FieldDecl::Create(Context,
3807 cast<RecordDecl>(CurContext),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003808 DS.getLocStart(),
3809 DS.getLocStart(),
Francois Pichet8e161ed2010-11-23 06:07:27 +00003810 /*IdentifierInfo=*/0,
3811 Context.getTypeDeclType(Record),
3812 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003813 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003814 /*InitStyle=*/ICIS_NoInit);
Francois Pichet8e161ed2010-11-23 06:07:27 +00003815 Anon->setImplicit();
3816
3817 // Add the anonymous struct object to the current context.
3818 CurContext->addDecl(Anon);
3819
3820 // Inject the members of the anonymous struct into the current
3821 // context and into the identifier resolver chain for name lookup
3822 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003823 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003824 Chain.push_back(Anon);
3825
Nico Weberee625af2012-02-01 00:41:00 +00003826 RecordDecl *RecordDef = Record->getDefinition();
3827 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3828 RecordDef, AS_none,
3829 Chain, true))
Francois Pichet8e161ed2010-11-23 06:07:27 +00003830 Anon->setInvalidDecl();
3831
3832 return Anon;
3833}
Steve Narofff0090632007-09-02 02:04:30 +00003834
Douglas Gregor10bd3682008-11-17 22:58:34 +00003835/// GetNameForDeclarator - Determine the full declaration name for the
3836/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00003837DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00003838 return GetNameFromUnqualifiedId(D.getName());
3839}
3840
Abramo Bagnara25777432010-08-11 22:01:17 +00003841/// \brief Retrieves the declaration name from a parsed unqualified-id.
3842DeclarationNameInfo
3843Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3844 DeclarationNameInfo NameInfo;
3845 NameInfo.setLoc(Name.StartLocation);
3846
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003847 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00003848
Fariborz Jahanian98a54032011-07-12 17:16:56 +00003849 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnara25777432010-08-11 22:01:17 +00003850 case UnqualifiedId::IK_Identifier:
3851 NameInfo.setName(Name.Identifier);
3852 NameInfo.setLoc(Name.StartLocation);
3853 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00003854
Abramo Bagnara25777432010-08-11 22:01:17 +00003855 case UnqualifiedId::IK_OperatorFunctionId:
3856 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3857 Name.OperatorFunctionId.Operator));
3858 NameInfo.setLoc(Name.StartLocation);
3859 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3860 = Name.OperatorFunctionId.SymbolLocations[0];
3861 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3862 = Name.EndLocation.getRawEncoding();
3863 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003864
Abramo Bagnara25777432010-08-11 22:01:17 +00003865 case UnqualifiedId::IK_LiteralOperatorId:
3866 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3867 Name.Identifier));
3868 NameInfo.setLoc(Name.StartLocation);
3869 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3870 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003871
Abramo Bagnara25777432010-08-11 22:01:17 +00003872 case UnqualifiedId::IK_ConversionFunctionId: {
3873 TypeSourceInfo *TInfo;
3874 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3875 if (Ty.isNull())
3876 return DeclarationNameInfo();
3877 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3878 Context.getCanonicalType(Ty)));
3879 NameInfo.setLoc(Name.StartLocation);
3880 NameInfo.setNamedTypeInfo(TInfo);
3881 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00003882 }
Abramo Bagnara25777432010-08-11 22:01:17 +00003883
3884 case UnqualifiedId::IK_ConstructorName: {
3885 TypeSourceInfo *TInfo;
3886 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3887 if (Ty.isNull())
3888 return DeclarationNameInfo();
3889 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3890 Context.getCanonicalType(Ty)));
3891 NameInfo.setLoc(Name.StartLocation);
3892 NameInfo.setNamedTypeInfo(TInfo);
3893 return NameInfo;
3894 }
3895
3896 case UnqualifiedId::IK_ConstructorTemplateId: {
3897 // In well-formed code, we can only have a constructor
3898 // template-id that refers to the current context, so go there
3899 // to find the actual type being constructed.
3900 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3901 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3902 return DeclarationNameInfo();
3903
3904 // Determine the type of the class being constructed.
3905 QualType CurClassType = Context.getTypeDeclType(CurClass);
3906
3907 // FIXME: Check two things: that the template-id names the same type as
3908 // CurClassType, and that the template-id does not occur when the name
3909 // was qualified.
3910
3911 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3912 Context.getCanonicalType(CurClassType)));
3913 NameInfo.setLoc(Name.StartLocation);
3914 // FIXME: should we retrieve TypeSourceInfo?
3915 NameInfo.setNamedTypeInfo(0);
3916 return NameInfo;
3917 }
3918
3919 case UnqualifiedId::IK_DestructorName: {
3920 TypeSourceInfo *TInfo;
3921 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3922 if (Ty.isNull())
3923 return DeclarationNameInfo();
3924 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3925 Context.getCanonicalType(Ty)));
3926 NameInfo.setLoc(Name.StartLocation);
3927 NameInfo.setNamedTypeInfo(TInfo);
3928 return NameInfo;
3929 }
3930
3931 case UnqualifiedId::IK_TemplateId: {
John McCall2b5289b2010-08-23 07:28:44 +00003932 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00003933 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3934 return Context.getNameForTemplate(TName, TNameLoc);
3935 }
3936
3937 } // switch (Name.getKind())
3938
David Blaikieb219cfc2011-09-23 05:06:16 +00003939 llvm_unreachable("Unknown name kind");
Douglas Gregor10bd3682008-11-17 22:58:34 +00003940}
3941
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003942static QualType getCoreType(QualType Ty) {
3943 do {
3944 if (Ty->isPointerType() || Ty->isReferenceType())
3945 Ty = Ty->getPointeeType();
3946 else if (Ty->isArrayType())
3947 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3948 else
3949 return Ty.withoutLocalFastQualifiers();
3950 } while (true);
3951}
3952
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00003953/// hasSimilarParameters - Determine whether the C++ functions Declaration
3954/// and Definition have "nearly" matching parameters. This heuristic is
3955/// used to improve diagnostics in the case where an out-of-line function
3956/// definition doesn't match any declaration within the class or namespace.
3957/// Also sets Params to the list of indices to the parameters that differ
3958/// between the declaration and the definition. If hasSimilarParameters
3959/// returns true and Params is empty, then all of the parameters match.
3960static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003961 FunctionDecl *Declaration,
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003962 FunctionDecl *Definition,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003963 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003964 Params.clear();
Douglas Gregor584049d2008-12-15 23:53:10 +00003965 if (Declaration->param_size() != Definition->param_size())
3966 return false;
3967 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3968 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3969 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3970
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003971 // The parameter types are identical
Matt Beaumont-Gay903d6dc2011-08-23 01:35:51 +00003972 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003973 continue;
3974
3975 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3976 QualType DefParamBaseTy = getCoreType(DefParamTy);
3977 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3978 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3979
3980 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3981 (DeclTyName && DeclTyName == DefTyName))
3982 Params.push_back(Idx);
3983 else // The two parameters aren't even close
Douglas Gregor584049d2008-12-15 23:53:10 +00003984 return false;
3985 }
3986
3987 return true;
3988}
3989
John McCall63b43852010-04-29 23:50:39 +00003990/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3991/// declarator needs to be rebuilt in the current instantiation.
3992/// Any bits of declarator which appear before the name are valid for
3993/// consideration here. That's specifically the type in the decl spec
3994/// and the base type in any member-pointer chunks.
3995static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3996 DeclarationName Name) {
3997 // The types we specifically need to rebuild are:
3998 // - typenames, typeofs, and decltypes
3999 // - types which will become injected class names
4000 // Of course, we also need to rebuild any type referencing such a
4001 // type. It's safest to just say "dependent", but we call out a
4002 // few cases here.
4003
4004 DeclSpec &DS = D.getMutableDeclSpec();
4005 switch (DS.getTypeSpecType()) {
4006 case DeclSpec::TST_typename:
4007 case DeclSpec::TST_typeofType:
Eli Friedmanb001de72011-10-06 23:00:33 +00004008 case DeclSpec::TST_underlyingType:
4009 case DeclSpec::TST_atomic: {
John McCall63b43852010-04-29 23:50:39 +00004010 // Grab the type from the parser.
4011 TypeSourceInfo *TSI = 0;
John McCallb3d87482010-08-24 05:47:05 +00004012 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall63b43852010-04-29 23:50:39 +00004013 if (T.isNull() || !T->isDependentType()) break;
4014
4015 // Make sure there's a type source info. This isn't really much
4016 // of a waste; most dependent types should have type source info
4017 // attached already.
4018 if (!TSI)
4019 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4020
4021 // Rebuild the type in the current instantiation.
4022 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4023 if (!TSI) return true;
4024
4025 // Store the new type back in the decl spec.
John McCallb3d87482010-08-24 05:47:05 +00004026 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4027 DS.UpdateTypeRep(LocType);
4028 break;
4029 }
4030
Richard Smithc4a83912012-10-01 20:35:07 +00004031 case DeclSpec::TST_decltype:
John McCallb3d87482010-08-24 05:47:05 +00004032 case DeclSpec::TST_typeofExpr: {
4033 Expr *E = DS.getRepAsExpr();
John McCall60d7b3a2010-08-24 06:29:42 +00004034 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallb3d87482010-08-24 05:47:05 +00004035 if (Result.isInvalid()) return true;
4036 DS.UpdateExprRep(Result.get());
John McCall63b43852010-04-29 23:50:39 +00004037 break;
4038 }
4039
4040 default:
4041 // Nothing to do for these decl specs.
4042 break;
4043 }
4044
4045 // It doesn't matter what order we do this in.
4046 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4047 DeclaratorChunk &Chunk = D.getTypeObject(I);
4048
4049 // The only type information in the declarator which can come
4050 // before the declaration name is the base type of a member
4051 // pointer.
4052 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4053 continue;
4054
4055 // Rebuild the scope specifier in-place.
4056 CXXScopeSpec &SS = Chunk.Mem.Scope();
4057 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4058 return true;
4059 }
4060
4061 return false;
4062}
4063
Anders Carlsson3242ee02011-07-04 16:28:17 +00004064Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00004065 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004066 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004067
4068 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregore7be1092012-04-30 18:13:01 +00004069 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004070 Dcl->setTopLevelDeclInObjCContainer();
4071
4072 return Dcl;
John McCall7cd088e2010-08-24 07:21:54 +00004073}
4074
Richard Smith162e1c12011-04-15 14:24:37 +00004075/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4076/// If T is the name of a class, then each of the following shall have a
4077/// name different from T:
4078/// - every static data member of class T;
4079/// - every member function of class T
4080/// - every member of class T that is itself a type;
4081/// \returns true if the declaration name violates these rules.
4082bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4083 DeclarationNameInfo NameInfo) {
4084 DeclarationName Name = NameInfo.getName();
4085
4086 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4087 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4088 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4089 return true;
4090 }
4091
4092 return false;
4093}
Douglas Gregor42acead2012-03-17 23:06:31 +00004094
Douglas Gregor69605872012-03-28 16:01:27 +00004095/// \brief Diagnose a declaration whose declarator-id has the given
4096/// nested-name-specifier.
4097///
4098/// \param SS The nested-name-specifier of the declarator-id.
4099///
4100/// \param DC The declaration context to which the nested-name-specifier
4101/// resolves.
4102///
4103/// \param Name The name of the entity being declared.
4104///
4105/// \param Loc The location of the name of the entity being declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004106///
4107/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregor69605872012-03-28 16:01:27 +00004108bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor42acead2012-03-17 23:06:31 +00004109 DeclarationName Name,
Douglas Gregor69605872012-03-28 16:01:27 +00004110 SourceLocation Loc) {
4111 DeclContext *Cur = CurContext;
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004112 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregor69605872012-03-28 16:01:27 +00004113 Cur = Cur->getParent();
4114
4115 // C++ [dcl.meaning]p1:
4116 // A declarator-id shall not be qualified except for the definition
4117 // of a member function (9.3) or static data member (9.4) outside of
4118 // its class, the definition or explicit instantiation of a function
4119 // or variable member of a namespace outside of its namespace, or the
4120 // definition of an explicit specialization outside of its namespace,
4121 // or the declaration of a friend function that is a member of
4122 // another class or namespace (11.3). [...]
4123
4124 // The user provided a superfluous scope specifier that refers back to the
4125 // class or namespaces in which the entity is already declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004126 //
4127 // class X {
4128 // void X::f();
4129 // };
Douglas Gregor69605872012-03-28 16:01:27 +00004130 if (Cur->Equals(DC)) {
Douglas Gregor75379452012-09-13 20:16:20 +00004131 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4132 : diag::err_member_extra_qualification)
Douglas Gregor42acead2012-03-17 23:06:31 +00004133 << Name << FixItHint::CreateRemoval(SS.getRange());
4134 SS.clear();
4135 return false;
4136 }
Douglas Gregor69605872012-03-28 16:01:27 +00004137
4138 // Check whether the qualifying scope encloses the scope of the original
4139 // declaration.
4140 if (!Cur->Encloses(DC)) {
4141 if (Cur->isRecord())
4142 Diag(Loc, diag::err_member_qualification)
4143 << Name << SS.getRange();
4144 else if (isa<TranslationUnitDecl>(DC))
4145 Diag(Loc, diag::err_invalid_declarator_global_scope)
4146 << Name << SS.getRange();
4147 else if (isa<FunctionDecl>(Cur))
4148 Diag(Loc, diag::err_invalid_declarator_in_function)
4149 << Name << SS.getRange();
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004150 else if (isa<BlockDecl>(Cur))
4151 Diag(Loc, diag::err_invalid_declarator_in_block)
4152 << Name << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004153 else
4154 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smitha1c4f7c2012-04-13 04:07:40 +00004155 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004156
Douglas Gregor42acead2012-03-17 23:06:31 +00004157 return true;
Douglas Gregor69605872012-03-28 16:01:27 +00004158 }
4159
4160 if (Cur->isRecord()) {
4161 // Cannot qualify members within a class.
4162 Diag(Loc, diag::err_member_qualification)
4163 << Name << SS.getRange();
4164 SS.clear();
4165
4166 // C++ constructors and destructors with incorrect scopes can break
4167 // our AST invariants by having the wrong underlying types. If
4168 // that's the case, then drop this declaration entirely.
4169 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4170 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4171 !Context.hasSameType(Name.getCXXNameType(),
4172 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4173 return true;
4174
4175 return false;
4176 }
Douglas Gregor42acead2012-03-17 23:06:31 +00004177
Douglas Gregor69605872012-03-28 16:01:27 +00004178 // C++11 [dcl.meaning]p1:
4179 // [...] "The nested-name-specifier of the qualified declarator-id shall
4180 // not begin with a decltype-specifer"
4181 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4182 while (SpecLoc.getPrefix())
4183 SpecLoc = SpecLoc.getPrefix();
4184 if (dyn_cast_or_null<DecltypeType>(
4185 SpecLoc.getNestedNameSpecifier()->getAsType()))
4186 Diag(Loc, diag::err_decltype_in_declarator)
4187 << SpecLoc.getTypeLoc().getSourceRange();
4188
Douglas Gregor42acead2012-03-17 23:06:31 +00004189 return false;
4190}
4191
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00004192NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4193 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnara25777432010-08-11 22:01:17 +00004194 // TODO: consider using NameInfo for diagnostic.
4195 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4196 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00004197
Chris Lattnere80a59c2007-07-25 00:24:17 +00004198 // All of these full declarators require an identifier. If it doesn't have
4199 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00004200 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00004201 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004202 Diag(D.getDeclSpec().getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004203 diag::err_declarator_need_ident)
4204 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00004205 return 0;
Douglas Gregor56c04582010-12-16 00:46:58 +00004206 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4207 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004208
Chris Lattner31e05722007-08-26 06:24:45 +00004209 // The scope passed in may not be a decl scope. Zip up the scope tree until
4210 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00004211 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004212 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00004213 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004214
John McCall63b43852010-04-29 23:50:39 +00004215 DeclContext *DC = CurContext;
4216 if (D.getCXXScopeSpec().isInvalid())
4217 D.setInvalidType();
4218 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6ccab972010-12-16 01:14:37 +00004219 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4220 UPPC_DeclarationQualifier))
4221 return 0;
4222
John McCall63b43852010-04-29 23:50:39 +00004223 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4224 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4225 if (!DC) {
4226 // If we could not compute the declaration context, it's because the
4227 // declaration context is dependent but does not refer to a class,
4228 // class template, or class template partial specialization. Complain
4229 // and return early, to avoid the coming semantic disaster.
4230 Diag(D.getIdentifierLoc(),
4231 diag::err_template_qualified_declarator_no_match)
4232 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4233 << D.getCXXScopeSpec().getRange();
John McCalld226f652010-08-21 09:40:31 +00004234 return 0;
John McCall63b43852010-04-29 23:50:39 +00004235 }
John McCall63b43852010-04-29 23:50:39 +00004236 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00004237
John McCall63b43852010-04-29 23:50:39 +00004238 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00004239 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCalld226f652010-08-21 09:40:31 +00004240 return 0;
John McCall63b43852010-04-29 23:50:39 +00004241
Douglas Gregor69605872012-03-28 16:01:27 +00004242 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4243 Diag(D.getIdentifierLoc(),
4244 diag::err_member_def_undefined_record)
4245 << Name << DC << D.getCXXScopeSpec().getRange();
4246 D.setInvalidType();
4247 } else if (!D.getDeclSpec().isFriendSpecified()) {
4248 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4249 Name, D.getIdentifierLoc())) {
4250 if (DC->isRecord())
Douglas Gregor42acead2012-03-17 23:06:31 +00004251 return 0;
Douglas Gregor69605872012-03-28 16:01:27 +00004252
4253 D.setInvalidType();
Douglas Gregor922fff22010-10-13 22:19:53 +00004254 }
John McCall63b43852010-04-29 23:50:39 +00004255 }
4256
4257 // Check whether we need to rebuild the type of the given
4258 // declaration in the current instantiation.
4259 if (EnteringContext && IsDependentContext &&
4260 TemplateParamLists.size() != 0) {
4261 ContextRAII SavedContext(*this, DC);
4262 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4263 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00004264 }
4265 }
Richard Smith162e1c12011-04-15 14:24:37 +00004266
4267 if (DiagnoseClassNameShadow(DC, NameInfo))
4268 // If this is a typedef, we'll end up spewing multiple diagnostics.
4269 // Just return early; it's safer.
4270 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4271 return 0;
Douglas Gregora6e937c2010-10-15 13:21:21 +00004272
John McCallbf1a0282010-06-04 23:28:52 +00004273 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4274 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004275
Douglas Gregord0937222010-12-13 22:49:22 +00004276 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4277 UPPC_DeclarationType))
4278 D.setInvalidType();
4279
Abramo Bagnara25777432010-08-11 22:01:17 +00004280 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00004281 ForRedeclaration);
4282
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004283 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00004284 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00004285 bool IsLinkageLookup = false;
Richard Smithdd9459f2013-08-13 18:18:50 +00004286 bool CreateBuiltins = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004287
4288 // If the declaration we're planning to build will be a function
4289 // or object with linkage, then look for another declaration with
4290 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smithdd9459f2013-08-13 18:18:50 +00004291 //
4292 // If the declaration we're planning to build will be declared with
4293 // external linkage in the translation unit, create any builtin with
4294 // the same name.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004295 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4296 /* Do nothing*/;
Richard Smithdd9459f2013-08-13 18:18:50 +00004297 else if (CurContext->isFunctionOrMethod() &&
4298 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4299 R->isFunctionType())) {
John McCall68263142009-11-18 22:49:29 +00004300 IsLinkageLookup = true;
Richard Smithdd9459f2013-08-13 18:18:50 +00004301 CreateBuiltins =
4302 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4303 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4304 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4305 CreateBuiltins = true;
John McCall68263142009-11-18 22:49:29 +00004306
4307 if (IsLinkageLookup)
4308 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004309
Richard Smithdd9459f2013-08-13 18:18:50 +00004310 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004311 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00004312 LookupQualifiedName(Previous, DC);
4313
Douglas Gregor69605872012-03-28 16:01:27 +00004314 // C++ [dcl.meaning]p1:
4315 // When the declarator-id is qualified, the declaration shall refer to a
4316 // previously declared member of the class or namespace to which the
4317 // qualifier refers (or, in the case of a namespace, of an element of the
4318 // inline namespace set of that namespace (7.3.1)) or to a specialization
4319 // thereof; [...]
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004320 //
Douglas Gregor69605872012-03-28 16:01:27 +00004321 // Note that we already checked the context above, and that we do not have
4322 // enough information to make sure that Previous contains the declaration
4323 // we want to match. For example, given:
Douglas Gregor584049d2008-12-15 23:53:10 +00004324 //
Douglas Gregor9d350972008-12-12 08:25:50 +00004325 // class X {
4326 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00004327 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00004328 // };
4329 //
Douglas Gregor584049d2008-12-15 23:53:10 +00004330 // void X::f(int) { } // ill-formed
4331 //
Douglas Gregor69605872012-03-28 16:01:27 +00004332 // In this case, Previous will point to the overload set
Douglas Gregor584049d2008-12-15 23:53:10 +00004333 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00004334 // matches.
Douglas Gregor69605872012-03-28 16:01:27 +00004335
4336 // C++ [dcl.meaning]p1:
4337 // [...] the member shall not merely have been introduced by a
4338 // using-declaration in the scope of the class or namespace nominated by
4339 // the nested-name-specifier of the declarator-id.
4340 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004341 }
4342
John McCall68263142009-11-18 22:49:29 +00004343 if (Previous.isSingleResult() &&
4344 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00004345 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004346 if (!D.isInvalidType())
Douglas Gregorcb8f9512011-10-20 17:58:49 +00004347 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4348 Previous.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004349
Douglas Gregor72c3f312008-12-05 18:15:24 +00004350 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00004351 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00004352 }
4353
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004354 // In C++, the previous declaration we find might be a tag type
4355 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00004356 // tag type. Note that this does does not apply if we're declaring a
4357 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00004358 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00004359 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00004360 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004361
Richard Smith3cdbbdc2013-03-06 01:37:38 +00004362 // Check that there are no default arguments other than in the parameters
4363 // of a function declaration (C++ only).
4364 if (getLangOpts().CPlusPlus)
4365 CheckExtraCXXDefaultArguments(D);
4366
Nico Webere6bb76c2012-12-23 00:40:46 +00004367 NamedDecl *New;
4368
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004369 bool AddToScope = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00004370 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00004371 if (TemplateParamLists.size()) {
4372 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCalld226f652010-08-21 09:40:31 +00004373 return 0;
Douglas Gregore542c862009-06-23 23:11:28 +00004374 }
Mike Stump1eb44332009-09-09 15:08:12 +00004375
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004376 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004377 } else if (R->isFunctionType()) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004378 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004379 TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004380 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004381 } else {
Larisse Voufoef4579c2013-08-06 01:03:05 +00004382 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4383 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004384 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004385
4386 if (New == 0)
John McCalld226f652010-08-21 09:40:31 +00004387 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004388
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004389 // If this has an identifier and is not an invalid redeclaration or
4390 // function template specialization, add it to the scope stack.
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004391 if (New->getDeclName() && AddToScope &&
Richard Smitha41c97a2013-09-20 01:15:31 +00004392 !(D.isRedeclaration() && New->isInvalidDecl())) {
4393 // Only make a locally-scoped extern declaration visible if it is the first
4394 // declaration of this entity. Qualified lookup for such an entity should
4395 // only find this declaration if there is no visible declaration of it.
4396 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4397 PushOnScopeChains(New, S, AddToContext);
4398 if (!AddToContext)
4399 CurContext->addHiddenDecl(New);
4400 }
Mike Stump1eb44332009-09-09 15:08:12 +00004401
John McCalld226f652010-08-21 09:40:31 +00004402 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00004403}
4404
Abramo Bagnara88adb982012-11-08 16:27:30 +00004405/// Helper method to turn variable array types into constant array
4406/// types in certain situations which would otherwise be errors (for
4407/// GCC compatibility).
Eli Friedman1ca48132009-02-21 00:44:51 +00004408static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4409 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00004410 bool &SizeIsNegative,
4411 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004412 // This method tries to turn a variable array into a constant
4413 // array even when the size isn't an ICE. This is necessary
4414 // for compatibility with code that depends on gcc's buggy
4415 // constant expression folding, like struct {char x[(int)(char*)2];}
4416 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004417 Oversized = 0;
4418
4419 if (T->isDependentType())
4420 return QualType();
4421
John McCall0953e762009-09-24 19:53:00 +00004422 QualifierCollector Qs;
4423 const Type *Ty = Qs.strip(T);
4424
4425 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004426 QualType Pointee = PTy->getPointeeType();
4427 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00004428 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4429 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00004430 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00004431 FixedType = Context.getPointerType(FixedType);
John McCall49f4e1c2010-12-10 11:01:00 +00004432 return Qs.apply(Context, FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00004433 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004434 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4435 QualType Inner = PTy->getInnerType();
4436 QualType FixedType =
4437 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4438 Oversized);
4439 if (FixedType.isNull()) return FixedType;
4440 FixedType = Context.getParenType(FixedType);
4441 return Qs.apply(Context, FixedType);
4442 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004443
4444 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00004445 if (!VLATy)
4446 return QualType();
4447 // FIXME: We should probably handle this case
4448 if (VLATy->getElementType()->isVariablyModifiedType())
4449 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Richard Smithaa9c3502011-12-07 00:43:50 +00004451 llvm::APSInt Res;
Eli Friedman1ca48132009-02-21 00:44:51 +00004452 if (!VLATy->getSizeExpr() ||
Richard Smithaa9c3502011-12-07 00:43:50 +00004453 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedman1ca48132009-02-21 00:44:51 +00004454 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00004455
Douglas Gregor2767ce22010-08-18 00:39:00 +00004456 // Check whether the array size is negative.
Douglas Gregor2767ce22010-08-18 00:39:00 +00004457 if (Res.isSigned() && Res.isNegative()) {
4458 SizeIsNegative = true;
4459 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004460 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004461
Douglas Gregor2767ce22010-08-18 00:39:00 +00004462 // Check whether the array is too large to be addressed.
4463 unsigned ActiveSizeBits
4464 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4465 Res);
4466 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4467 Oversized = Res;
4468 return QualType();
4469 }
4470
4471 return Context.getConstantArrayType(VLATy->getElementType(),
4472 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00004473}
4474
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004475static void
4476FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie39e6ab42013-02-18 22:06:02 +00004477 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4478 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4479 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4480 DstPTL.getPointeeLoc());
4481 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004482 return;
4483 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004484 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4485 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4486 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4487 DstPTL.getInnerLoc());
4488 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4489 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004490 return;
4491 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004492 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4493 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4494 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4495 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004496 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie39e6ab42013-02-18 22:06:02 +00004497 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4498 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4499 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004500}
4501
Abramo Bagnara88adb982012-11-08 16:27:30 +00004502/// Helper method to turn variable array types into constant array
4503/// types in certain situations which would otherwise be errors (for
4504/// GCC compatibility).
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004505static TypeSourceInfo*
4506TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4507 ASTContext &Context,
4508 bool &SizeIsNegative,
4509 llvm::APSInt &Oversized) {
4510 QualType FixedTy
4511 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4512 SizeIsNegative, Oversized);
4513 if (FixedTy.isNull())
4514 return 0;
4515 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4516 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4517 FixedTInfo->getTypeLoc());
4518 return FixedTInfo;
4519}
4520
Richard Smith5ea6ef42013-01-10 23:43:47 +00004521/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith662f41b2013-06-18 20:15:12 +00004522/// that it can be found later for redeclarations. We include any extern "C"
4523/// declaration that is not visible in the translation unit here, not just
4524/// function-scope declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004525void
Richard Smith662f41b2013-06-18 20:15:12 +00004526Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithaa4bc182013-06-30 09:48:50 +00004527 if (!getLangOpts().CPlusPlus &&
4528 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4529 // Don't need to track declarations in the TU in C.
4530 return;
4531
Douglas Gregor63935192009-03-02 00:19:53 +00004532 // Note that we have a locally-scoped external with this name.
Richard Smithaa4bc182013-06-30 09:48:50 +00004533 // FIXME: There can be multiple such declarations if they are functions marked
4534 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith5ea6ef42013-01-10 23:43:47 +00004535 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor63935192009-03-02 00:19:53 +00004536}
4537
Richard Smith662f41b2013-06-18 20:15:12 +00004538NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregorec12ce22011-07-28 14:20:37 +00004539 if (ExternalSource) {
4540 // Load locally-scoped external decls from the external source.
Richard Smith662f41b2013-06-18 20:15:12 +00004541 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregorec12ce22011-07-28 14:20:37 +00004542 SmallVector<NamedDecl *, 4> Decls;
Richard Smith5ea6ef42013-01-10 23:43:47 +00004543 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregorec12ce22011-07-28 14:20:37 +00004544 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4545 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith5ea6ef42013-01-10 23:43:47 +00004546 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4547 if (Pos == LocallyScopedExternCDecls.end())
4548 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregorec12ce22011-07-28 14:20:37 +00004549 }
4550 }
Richard Smith662f41b2013-06-18 20:15:12 +00004551
4552 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola87bcee82013-10-19 16:55:03 +00004553 return D ? D->getMostRecentDecl() : 0;
Douglas Gregorec12ce22011-07-28 14:20:37 +00004554}
4555
Eli Friedman85a53192009-04-07 19:37:57 +00004556/// \brief Diagnose function specifiers on a declaration of an identifier that
4557/// does not identify a function.
Richard Smithc7f81162013-03-18 22:52:47 +00004558void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman85a53192009-04-07 19:37:57 +00004559 // FIXME: We should probably indicate the identifier in question to avoid
4560 // confusion for constructs like "inline int a(), b;"
Richard Smithc7f81162013-03-18 22:52:47 +00004561 if (DS.isInlineSpecified())
4562 Diag(DS.getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004563 diag::err_inline_non_function);
4564
Richard Smithc7f81162013-03-18 22:52:47 +00004565 if (DS.isVirtualSpecified())
4566 Diag(DS.getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004567 diag::err_virtual_non_function);
4568
Richard Smithc7f81162013-03-18 22:52:47 +00004569 if (DS.isExplicitSpecified())
4570 Diag(DS.getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004571 diag::err_explicit_non_function);
Richard Smithde03c152013-01-17 22:16:11 +00004572
Richard Smithc7f81162013-03-18 22:52:47 +00004573 if (DS.isNoreturnSpecified())
4574 Diag(DS.getNoreturnSpecLoc(),
Richard Smithde03c152013-01-17 22:16:11 +00004575 diag::err_noreturn_non_function);
Eli Friedman85a53192009-04-07 19:37:57 +00004576}
4577
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004578NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004579Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004580 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004581 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4582 if (D.getCXXScopeSpec().isSet()) {
4583 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4584 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004585 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004586 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00004587 DC = CurContext;
4588 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004589 }
4590
Richard Smithc7f81162013-03-18 22:52:47 +00004591 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +00004592
Richard Smithaf1fc7a2011-08-15 21:04:07 +00004593 if (D.getDeclSpec().isConstexprSpecified())
4594 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4595 << 1;
Eli Friedman63054b32009-04-19 20:27:55 +00004596
Douglas Gregoraef01992010-07-13 06:37:01 +00004597 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4598 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4599 << D.getName().getSourceRange();
4600 return 0;
4601 }
4602
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004603 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004604 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004605
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004606 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004607 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00004608
Richard Smith3e4c6c42011-05-05 21:57:07 +00004609 CheckTypedefForVariablyModifiedType(S, NewTD);
4610
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004611 bool Redeclaration = D.isRedeclaration();
4612 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4613 D.setRedeclaration(Redeclaration);
4614 return ND;
Richard Smith162e1c12011-04-15 14:24:37 +00004615}
4616
Richard Smith3e4c6c42011-05-05 21:57:07 +00004617void
4618Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004619 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4620 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004621 // Note that variably modified types must be fixed before merging the decl so
4622 // that redeclarations will match.
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004623 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4624 QualType T = TInfo->getType();
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004625 if (T->isVariablyModifiedType()) {
John McCall781472f2010-08-25 08:40:02 +00004626 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004627
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004628 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004629 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004630 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004631 TypeSourceInfo *FixedTInfo =
4632 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4633 SizeIsNegative,
4634 Oversized);
4635 if (FixedTInfo) {
Richard Smith162e1c12011-04-15 14:24:37 +00004636 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004637 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedman1ca48132009-02-21 00:44:51 +00004638 } else {
4639 if (SizeIsNegative)
Richard Smith162e1c12011-04-15 14:24:37 +00004640 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00004641 else if (T->isVariableArrayType())
Richard Smith162e1c12011-04-15 14:24:37 +00004642 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00004643 else if (Oversized.getBoolValue())
David Blaikied662a792011-10-19 22:56:21 +00004644 Diag(NewTD->getLocation(), diag::err_array_too_large)
4645 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00004646 else
Richard Smith162e1c12011-04-15 14:24:37 +00004647 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004648 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00004649 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004650 }
4651 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00004652}
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004653
Richard Smith3e4c6c42011-05-05 21:57:07 +00004654
4655/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4656/// declares a typedef-name, either using the 'typedef' type specifier or via
4657/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4658NamedDecl*
4659Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4660 LookupResult &Previous, bool &Redeclaration) {
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004661 // Merge the decl with the existing one if appropriate. If the decl is
4662 // in an outer scope, it isn't the same thing.
Richard Smith3e4c6c42011-05-05 21:57:07 +00004663 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregorcc209452011-03-07 16:54:27 +00004664 /*ExplicitInstantiationOrSpecialization=*/false);
Douglas Gregor7dc80e12013-01-09 00:47:56 +00004665 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004666 if (!Previous.empty()) {
4667 Redeclaration = true;
Richard Smith162e1c12011-04-15 14:24:37 +00004668 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004669 }
4670
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004671 // If this is the C FILE type, notify the AST context.
4672 if (IdentifierInfo *II = NewTD->getIdentifier())
4673 if (!NewTD->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004674 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stump782fa302009-07-28 02:25:19 +00004675 if (II->isStr("FILE"))
4676 Context.setFILEDecl(NewTD);
4677 else if (II->isStr("jmp_buf"))
4678 Context.setjmp_bufDecl(NewTD);
4679 else if (II->isStr("sigjmp_buf"))
4680 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00004681 else if (II->isStr("ucontext_t"))
4682 Context.setucontext_tDecl(NewTD);
Mike Stump782fa302009-07-28 02:25:19 +00004683 }
4684
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004685 return NewTD;
4686}
4687
Douglas Gregor8f301052009-02-24 19:23:27 +00004688/// \brief Determines whether the given declaration is an out-of-scope
4689/// previous declaration.
4690///
4691/// This routine should be invoked when name lookup has found a
4692/// previous declaration (PrevDecl) that is not in the scope where a
4693/// new declaration by the same name is being introduced. If the new
4694/// declaration occurs in a local scope, previous declarations with
4695/// linkage may still be considered previous declarations (C99
4696/// 6.2.2p4-5, C++ [basic.link]p6).
4697///
4698/// \param PrevDecl the previous declaration found by name
4699/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00004700///
Douglas Gregor8f301052009-02-24 19:23:27 +00004701/// \param DC the context in which the new declaration is being
4702/// declared.
4703///
4704/// \returns true if PrevDecl is an out-of-scope previous declaration
4705/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00004706static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00004707isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4708 ASTContext &Context) {
4709 if (!PrevDecl)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004710 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004711
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004712 if (!PrevDecl->hasLinkage())
4713 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004714
David Blaikie4e4d0842012-03-11 07:00:24 +00004715 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor8f301052009-02-24 19:23:27 +00004716 // C++ [basic.link]p6:
4717 // If there is a visible declaration of an entity with linkage
4718 // having the same name and type, ignoring entities declared
4719 // outside the innermost enclosing namespace scope, the block
4720 // scope declaration declares that same entity and receives the
4721 // linkage of the previous declaration.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004722 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor8f301052009-02-24 19:23:27 +00004723 if (!OuterContext->isFunctionOrMethod())
4724 // This rule only applies to block-scope declarations.
4725 return false;
Douglas Gregor757c6002010-08-27 22:55:10 +00004726
4727 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4728 if (PrevOuterContext->isRecord())
4729 // We found a member function: ignore it.
4730 return false;
4731
4732 // Find the innermost enclosing namespace for the new and
4733 // previous declarations.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004734 OuterContext = OuterContext->getEnclosingNamespaceContext();
4735 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump1eb44332009-09-09 15:08:12 +00004736
Douglas Gregor757c6002010-08-27 22:55:10 +00004737 // The previous declaration is in a different namespace, so it
4738 // isn't the same function.
4739 if (!OuterContext->Equals(PrevOuterContext))
4740 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004741 }
4742
Douglas Gregor8f301052009-02-24 19:23:27 +00004743 return true;
4744}
4745
John McCallb6217662010-03-15 10:12:16 +00004746static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4747 CXXScopeSpec &SS = D.getCXXScopeSpec();
4748 if (!SS.isSet()) return;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00004749 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +00004750}
4751
John McCallf85e1932011-06-15 23:02:42 +00004752bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4753 QualType type = decl->getType();
4754 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4755 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4756 // Various kinds of declaration aren't allowed to be __autoreleasing.
4757 unsigned kind = -1U;
4758 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4759 if (var->hasAttr<BlocksAttr>())
4760 kind = 0; // __block
4761 else if (!var->hasLocalStorage())
4762 kind = 1; // global
4763 } else if (isa<ObjCIvarDecl>(decl)) {
4764 kind = 3; // ivar
4765 } else if (isa<FieldDecl>(decl)) {
4766 kind = 2; // field
4767 }
4768
4769 if (kind != -1U) {
4770 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4771 << kind;
4772 }
4773 } else if (lifetime == Qualifiers::OCL_None) {
4774 // Try to infer lifetime.
4775 if (!type->isObjCLifetimeType())
4776 return false;
4777
4778 lifetime = type->getObjCARCImplicitLifetime();
4779 type = Context.getLifetimeQualifiedType(type, lifetime);
4780 decl->setType(type);
4781 }
4782
4783 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4784 // Thread-local variables cannot have lifetime.
4785 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smith38afbc72013-04-13 02:43:54 +00004786 var->getTLSKind()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004787 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004788 << var->getType();
4789 return true;
4790 }
4791 }
4792
4793 return false;
4794}
4795
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004796static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4797 // 'weak' only applies to declarations with external linkage.
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004798 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004799 if (!ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004800 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4801 ND.dropAttr<WeakAttr>();
4802 }
4803 }
4804 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004805 if (ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004806 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4807 ND.dropAttr<WeakRefAttr>();
4808 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004809 }
Reid Klecknera7225342013-05-20 14:02:37 +00004810
4811 // 'selectany' only applies to externally visible varable declarations.
4812 // It does not apply to functions.
4813 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4814 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4815 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4816 ND.dropAttr<SelectAnyAttr>();
4817 }
4818 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004819}
4820
John McCallb421d922013-04-02 02:48:58 +00004821/// Given that we are within the definition of the given function,
4822/// will that definition behave like C99's 'inline', where the
4823/// definition is discarded except for optimization purposes?
4824static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4825 // Try to avoid calling GetGVALinkageForFunction.
4826
4827 // All cases of this require the 'inline' keyword.
4828 if (!FD->isInlined()) return false;
4829
4830 // This is only possible in C++ with the gnu_inline attribute.
4831 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4832 return false;
4833
4834 // Okay, go ahead and call the relatively-more-expensive function.
4835
4836#ifndef NDEBUG
4837 // AST quite reasonably asserts that it's working on a function
4838 // definition. We don't really have a way to tell it that we're
4839 // currently defining the function, so just lie to it in +Asserts
4840 // builds. This is an awful hack.
4841 FD->setLazyBody(1);
4842#endif
4843
4844 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4845
4846#ifndef NDEBUG
4847 FD->setLazyBody(0);
4848#endif
4849
4850 return isC99Inline;
4851}
4852
Richard Smithaa4bc182013-06-30 09:48:50 +00004853/// Determine whether a variable is extern "C" prior to attaching
4854/// an initializer. We can't just call isExternC() here, because that
4855/// will also compute and cache whether the declaration is externally
4856/// visible, which might change when we attach the initializer.
4857///
4858/// This can only be used if the declaration is known to not be a
4859/// redeclaration of an internal linkage declaration.
4860///
4861/// For instance:
4862///
4863/// auto x = []{};
4864///
4865/// Attaching the initializer here makes this declaration not externally
4866/// visible, because its type has internal linkage.
4867///
4868/// FIXME: This is a hack.
4869template<typename T>
4870static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4871 if (S.getLangOpts().CPlusPlus) {
4872 // In C++, the overloadable attribute negates the effects of extern "C".
4873 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4874 return false;
4875 }
4876 return D->isExternC();
4877}
4878
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004879static bool shouldConsiderLinkage(const VarDecl *VD) {
4880 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4881 if (DC->isFunctionOrMethod())
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004882 return VD->hasExternalStorage();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004883 if (DC->isFileContext())
4884 return true;
4885 if (DC->isRecord())
4886 return false;
4887 llvm_unreachable("Unexpected context");
4888}
4889
4890static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4891 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4892 if (DC->isFileContext() || DC->isFunctionOrMethod())
4893 return true;
4894 if (DC->isRecord())
4895 return false;
4896 llvm_unreachable("Unexpected context");
4897}
4898
Richard Smitha41c97a2013-09-20 01:15:31 +00004899/// Adjust the \c DeclContext for a function or variable that might be a
4900/// function-local external declaration.
4901bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4902 if (!DC->isFunctionOrMethod())
4903 return false;
4904
4905 // If this is a local extern function or variable declared within a function
4906 // template, don't add it into the enclosing namespace scope until it is
4907 // instantiated; it might have a dependent type right now.
4908 if (DC->isDependentContext())
4909 return true;
4910
4911 // C++11 [basic.link]p7:
4912 // When a block scope declaration of an entity with linkage is not found to
4913 // refer to some other declaration, then that entity is a member of the
4914 // innermost enclosing namespace.
4915 //
4916 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4917 // semantically-enclosing namespace, not a lexically-enclosing one.
4918 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4919 DC = DC->getParent();
4920 return true;
4921}
4922
Larisse Voufoef4579c2013-08-06 01:03:05 +00004923NamedDecl *
Chris Lattner16c5dea2010-10-10 18:16:20 +00004924Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004925 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufoef4579c2013-08-06 01:03:05 +00004926 MultiTemplateParamsArg TemplateParamLists,
4927 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004928 QualType R = TInfo->getType();
Abramo Bagnara25777432010-08-11 22:01:17 +00004929 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004930
Douglas Gregor16573fa2010-04-19 22:54:31 +00004931 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00004932 VarDecl::StorageClass SC =
4933 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Gouly19dbb202013-01-23 11:56:20 +00004934
Richard Smitha41c97a2013-09-20 01:15:31 +00004935 DeclContext *OriginalDC = DC;
4936 bool IsLocalExternDecl = SC == SC_Extern &&
4937 adjustContextForLocalExternDecl(DC);
4938
Richard Smithdf4cc0a2013-04-15 08:33:22 +00004939 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004940 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4941 // half array type (unless the cl_khr_fp16 extension is enabled).
4942 if (Context.getBaseElementType(R)->isHalfType()) {
4943 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4944 D.setInvalidType();
4945 }
4946 }
4947
Douglas Gregor16573fa2010-04-19 22:54:31 +00004948 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004949 // mutable can only appear on non-static class members, so it's always
4950 // an error here
4951 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004952 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004953 SC = SC_None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004954 }
John McCallb421d922013-04-02 02:48:58 +00004955
Richard Smith9109bf12013-06-17 01:34:01 +00004956 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4957 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4958 D.getDeclSpec().getStorageClassSpecLoc())) {
4959 // In C++11, the 'register' storage class specifier is deprecated.
4960 // Suppress the warning in system macros, it's used in macros in some
4961 // popular C system headers, such as in glibc's htonl() macro.
4962 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4963 diag::warn_deprecated_register)
4964 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4965 }
4966
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004967 IdentifierInfo *II = Name.getAsIdentifierInfo();
4968 if (!II) {
4969 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorb5a01872011-10-09 18:55:59 +00004970 << Name;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004971 return 0;
4972 }
4973
Richard Smithc7f81162013-03-18 22:52:47 +00004974 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor021c3b32009-03-11 23:00:04 +00004975
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00004976 if (!DC->isRecord() && S->getFnParent() == 0) {
4977 // C99 6.9p2: The storage-class specifiers auto and register shall not
4978 // appear in the declaration specifiers in an external declaration.
John McCalld931b082010-08-26 03:08:43 +00004979 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004980 // If this is a register variable with an asm label specified, then this
4981 // is a GNU extension.
John McCalld931b082010-08-26 03:08:43 +00004982 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004983 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4984 else
4985 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004986 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004987 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004988 }
Richard Smith9109bf12013-06-17 01:34:01 +00004989
David Blaikie4e4d0842012-03-11 07:00:24 +00004990 if (getLangOpts().OpenCL) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004991 // Set up the special work-group-local storage class for variables in the
4992 // OpenCL __local address space.
Rafael Espindola0db661e2012-12-21 01:21:33 +00004993 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004994 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola0db661e2012-12-21 01:21:33 +00004995 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00004996
Guy Benyei21f18c42013-02-07 10:55:47 +00004997 // OpenCL v1.2 s6.9.b p4:
4998 // The sampler type cannot be used with the __local and __global address
4999 // space qualifiers.
5000 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5001 R.getAddressSpace() == LangAS::opencl_global)) {
5002 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5003 }
5004
Guy Benyeie6b9d802013-01-20 12:31:11 +00005005 // OpenCL 1.2 spec, p6.9 r:
5006 // The event type cannot be used to declare a program scope variable.
5007 // The event type cannot be used with the __local, __constant and __global
5008 // address space qualifiers.
5009 if (R->isEventT()) {
5010 if (S->getParent() == 0) {
5011 Diag(D.getLocStart(), diag::err_event_t_global_var);
5012 D.setInvalidType();
5013 }
5014
5015 if (R.getAddressSpace()) {
5016 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5017 D.setInvalidType();
5018 }
5019 }
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005020 }
5021
Larisse Voufoef4579c2013-08-06 01:03:05 +00005022 bool IsExplicitSpecialization = false;
5023 bool IsVariableTemplateSpecialization = false;
5024 bool IsPartialSpecialization = false;
Larisse Voufo4a919892013-08-14 03:09:19 +00005025 bool IsVariableTemplate = false;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005026 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo567f9172013-08-22 00:59:14 +00005027 VarDecl *NewVD = 0;
5028 VarTemplateDecl *NewTemplate = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00005029 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005030 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005031 D.getIdentifierLoc(), II,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005032 R, TInfo, SC);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005033
5034 if (D.isInvalidType())
5035 NewVD->setInvalidDecl();
5036 } else {
Larisse Voufo567f9172013-08-22 00:59:14 +00005037 bool Invalid = false;
5038
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005039 if (DC->isRecord() && !CurContext->isRecord()) {
5040 // This is an out-of-line definition of a static data member.
Rafael Espindola3882aed2013-06-19 13:41:54 +00005041 switch (SC) {
5042 case SC_None:
5043 break;
5044 case SC_Static:
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005045 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5046 diag::err_static_out_of_line)
5047 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola3882aed2013-06-19 13:41:54 +00005048 break;
5049 case SC_Auto:
5050 case SC_Register:
5051 case SC_Extern:
5052 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5053 // to names of variables declared in a block or to function parameters.
5054 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5055 // of class members
5056
5057 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5058 diag::err_storage_class_for_static_member)
5059 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5060 break;
5061 case SC_PrivateExtern:
5062 llvm_unreachable("C storage class in c++!");
5063 case SC_OpenCLWorkGroupLocal:
5064 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindolaea4b1112013-04-04 21:21:25 +00005065 }
Larisse Voufo06935f32013-08-06 03:43:07 +00005066 }
5067
Richard Smithb9c64d82012-02-16 20:41:22 +00005068 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005069 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5070 if (RD->isLocalClass())
5071 Diag(D.getIdentifierLoc(),
5072 diag::err_static_data_member_not_allowed_in_local_class)
5073 << Name << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00005074
Richard Smithb9c64d82012-02-16 20:41:22 +00005075 // C++98 [class.union]p1: If a union contains a static data member,
5076 // the program is ill-formed. C++11 drops this restriction.
5077 if (RD->isUnion())
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005078 Diag(D.getIdentifierLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005079 getLangOpts().CPlusPlus11
Richard Smithb9c64d82012-02-16 20:41:22 +00005080 ? diag::warn_cxx98_compat_static_data_member_in_union
5081 : diag::ext_static_data_member_in_union) << Name;
5082 // We conservatively disallow static data members in anonymous structs.
5083 else if (!RD->getDeclName())
5084 Diag(D.getIdentifierLoc(),
5085 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005086 << Name << RD->isUnion();
5087 }
5088 }
5089
Larisse Voufoef4579c2013-08-06 01:03:05 +00005090 NamedDecl *PrevDecl = 0;
5091 if (Previous.begin() != Previous.end())
5092 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5093 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5094
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005095 // Match up the template parameter lists with the scope specifier, then
5096 // determine whether we have a template or a template specialization.
Larisse Voufo567f9172013-08-22 00:59:14 +00005097 TemplateParameterList *TemplateParams =
5098 MatchTemplateParametersToScopeSpecifier(
5099 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5100 D.getCXXScopeSpec(), TemplateParamLists,
5101 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufoef4579c2013-08-06 01:03:05 +00005102 if (TemplateParams) {
5103 if (!TemplateParams->size() &&
5104 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005105 // There is an extraneous 'template<>' for this variable. Complain
5106 // about it, but allow the declaration of the variable.
5107 Diag(TemplateParams->getTemplateLoc(),
5108 diag::err_template_variable_noparams)
5109 << II
5110 << SourceRange(TemplateParams->getTemplateLoc(),
5111 TemplateParams->getRAngleLoc());
Larisse Voufoef4579c2013-08-06 01:03:05 +00005112 } else {
5113 // Only C++1y supports variable templates (N3651).
5114 Diag(D.getIdentifierLoc(),
5115 getLangOpts().CPlusPlus1y
5116 ? diag::warn_cxx11_compat_variable_template
5117 : diag::ext_variable_template);
5118
5119 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5120 // This is an explicit specialization or a partial specialization.
5121 // Check that we can declare a specialization here
5122
5123 IsVariableTemplateSpecialization = true;
5124 IsPartialSpecialization = TemplateParams->size() > 0;
5125
5126 } else { // if (TemplateParams->size() > 0)
Larisse Voufo06935f32013-08-06 03:43:07 +00005127 // This is a template declaration.
Larisse Voufo4a919892013-08-14 03:09:19 +00005128 IsVariableTemplate = true;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005129
5130 // Check that we can declare a template here.
5131 if (CheckTemplateDeclScope(S, TemplateParams))
5132 return 0;
5133
5134 // If there is a previous declaration with the same name, check
5135 // whether this is a valid redeclaration.
5136 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5137 PrevDecl = PrevVarTemplate = 0;
5138
5139 if (PrevVarTemplate) {
5140 // Ensure that the template parameter lists are compatible.
5141 if (!TemplateParameterListsAreEqual(
5142 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5143 /*Complain=*/true, TPL_TemplateMatch))
5144 return 0;
5145 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5146 // Maybe we will complain about the shadowed template parameter.
5147 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5148
5149 // Just pretend that we didn't see the previous declaration.
5150 PrevDecl = 0;
5151 } else if (PrevDecl) {
5152 // C++ [temp]p5:
5153 // ... a template name declared in namespace scope or in class
5154 // scope shall be unique in that scope.
5155 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5156 << Name;
5157 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5158 return 0;
5159 }
5160
5161 // Check the template parameter list of this declaration, possibly
5162 // merging in the template parameter list from the previous variable
5163 // template declaration.
5164 if (CheckTemplateParameterList(
5165 TemplateParams,
5166 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5167 : 0,
5168 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5169 DC->isDependentContext())
5170 ? TPC_ClassTemplateMember
5171 : TPC_VarTemplate))
5172 Invalid = true;
5173
5174 if (D.getCXXScopeSpec().isSet()) {
5175 // If the name of the template was qualified, we must be defining
5176 // the template out-of-line.
5177 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5178 !PrevVarTemplate) {
Richard Smith4e9686b2013-08-09 04:35:01 +00005179 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5180 << Name << DC << /*IsDefinition*/true
5181 << D.getCXXScopeSpec().getRange();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005182 Invalid = true;
5183 }
5184 }
5185 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005186 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00005187 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5188 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5189
5190 // We have encountered something that the user meant to be a
5191 // specialization (because it has explicitly-specified template
5192 // arguments) but that was not introduced with a "template<>" (or had
5193 // too few of them).
5194 // FIXME: Differentiate between attempts for explicit instantiations
5195 // (starting with "template") and the rest.
5196 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5197 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5198 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5199 "template<> ");
5200 IsVariableTemplateSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00005201 }
Mike Stump1eb44332009-09-09 15:08:12 +00005202
Larisse Voufoef4579c2013-08-06 01:03:05 +00005203 if (IsVariableTemplateSpecialization) {
5204 if (!PrevVarTemplate) {
5205 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5206 << IsPartialSpecialization;
5207 return 0;
5208 }
5209
5210 SourceLocation TemplateKWLoc =
5211 TemplateParamLists.size() > 0
5212 ? TemplateParamLists[0]->getTemplateLoc()
5213 : SourceLocation();
5214 DeclResult Res = ActOnVarTemplateSpecialization(
5215 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5216 IsPartialSpecialization);
5217 if (Res.isInvalid())
5218 return 0;
5219 NewVD = cast<VarDecl>(Res.get());
5220 AddToScope = false;
5221 } else
5222 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5223 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedman63054b32009-04-19 20:27:55 +00005224
Larisse Voufo567f9172013-08-22 00:59:14 +00005225 // If this is supposed to be a variable template, create it as such.
5226 if (IsVariableTemplate) {
5227 NewTemplate =
5228 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5229 TemplateParams, NewVD, PrevVarTemplate);
5230 NewVD->setDescribedVarTemplate(NewTemplate);
5231 }
5232
Richard Smith483b9f32011-02-21 20:05:19 +00005233 // If this decl has an auto type in need of deduction, make a note of the
5234 // Decl so we can diagnose uses of it in its own initializer.
Richard Smitha2c36462013-04-26 16:15:35 +00005235 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smith483b9f32011-02-21 20:05:19 +00005236 ParsingInitForAutoVars.insert(NewVD);
Richard Smith34b41d92011-02-20 03:19:35 +00005237
Larisse Voufo567f9172013-08-22 00:59:14 +00005238 if (D.isInvalidType() || Invalid) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005239 NewVD->setInvalidDecl();
Larisse Voufo567f9172013-08-22 00:59:14 +00005240 if (NewTemplate)
5241 NewTemplate->setInvalidDecl();
5242 }
Mike Stump1eb44332009-09-09 15:08:12 +00005243
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005244 SetNestedNameSpecifier(NewVD, D);
John McCallb6217662010-03-15 10:12:16 +00005245
Larisse Voufoef4579c2013-08-06 01:03:05 +00005246 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5247 if (TemplateParams && TemplateParamLists.size() > 1 &&
5248 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5249 NewVD->setTemplateParameterListsInfo(
5250 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5251 } else if (IsVariableTemplateSpecialization ||
5252 (!TemplateParams && TemplateParamLists.size() > 0 &&
5253 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005254 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005255 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00005256 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005257 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005258
Richard Smith7ca48502012-02-13 22:16:19 +00005259 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithdd4b3502011-12-25 21:17:58 +00005260 NewVD->setConstexpr(true);
Abramo Bagnara9b934882010-06-12 08:15:14 +00005261 }
5262
Douglas Gregore3895852011-09-12 18:37:38 +00005263 // Set the lexical context. If the declarator has a C++ scope specifier, the
5264 // lexical context will be different from the semantic context.
5265 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo567f9172013-08-22 00:59:14 +00005266 if (NewTemplate)
5267 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregore3895852011-09-12 18:37:38 +00005268
Richard Smitha41c97a2013-09-20 01:15:31 +00005269 if (IsLocalExternDecl)
5270 NewVD->setLocalExternDecl();
5271
Richard Smithec642442013-04-12 22:46:28 +00005272 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005273 if (NewVD->hasLocalStorage()) {
5274 // C++11 [dcl.stc]p4:
5275 // When thread_local is applied to a variable of block scope the
5276 // storage-class-specifier static is implied if it does not appear
5277 // explicitly.
5278 // Core issue: 'static' is not implied if the variable is declared
5279 // 'extern'.
5280 if (SCSpec == DeclSpec::SCS_unspecified &&
5281 TSCS == DeclSpec::TSCS_thread_local &&
5282 DC->isFunctionOrMethod())
5283 NewVD->setTSCSpec(TSCS);
5284 else
5285 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5286 diag::err_thread_non_global)
5287 << DeclSpec::getSpecifierName(TSCS);
5288 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithec642442013-04-12 22:46:28 +00005289 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5290 diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00005291 else
Enea Zaffanelladc173842013-05-04 08:27:07 +00005292 NewVD->setTSCSpec(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00005293 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005294
John McCallb421d922013-04-02 02:48:58 +00005295 // C99 6.7.4p3
5296 // An inline definition of a function with external linkage shall
5297 // not contain a definition of a modifiable object with static or
5298 // thread storage duration...
5299 // We only apply this when the function is required to be defined
5300 // elsewhere, i.e. when the function is not 'extern inline'. Note
5301 // that a local variable with thread storage duration still has to
5302 // be marked 'static'. Also note that it's possible to get these
5303 // semantics in C++ using __attribute__((gnu_inline)).
5304 if (SC == SC_Static && S->getFnParent() != 0 &&
5305 !NewVD->getType().isConstQualified()) {
5306 FunctionDecl *CurFD = getCurFunctionDecl();
5307 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5308 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5309 diag::warn_static_local_in_extern_inline);
5310 MaybeSuggestAddingStaticToDecl(CurFD);
5311 }
5312 }
5313
Douglas Gregord023aec2011-09-09 20:53:38 +00005314 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00005315 if (IsVariableTemplateSpecialization)
5316 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5317 << (IsPartialSpecialization ? 1 : 0)
5318 << FixItHint::CreateRemoval(
5319 D.getDeclSpec().getModulePrivateSpecLoc());
5320 else if (IsExplicitSpecialization)
Douglas Gregord023aec2011-09-09 20:53:38 +00005321 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5322 << 2
5323 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregore3895852011-09-12 18:37:38 +00005324 else if (NewVD->hasLocalStorage())
5325 Diag(NewVD->getLocation(), diag::err_module_private_local)
5326 << 0 << NewVD->getDeclName()
5327 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5328 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo567f9172013-08-22 00:59:14 +00005329 else {
Douglas Gregord023aec2011-09-09 20:53:38 +00005330 NewVD->setModulePrivate();
Larisse Voufo567f9172013-08-22 00:59:14 +00005331 if (NewTemplate)
5332 NewTemplate->setModulePrivate();
5333 }
Douglas Gregord023aec2011-09-09 20:53:38 +00005334 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00005335
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005336 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005337 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005338
Richard Smithbe507b62013-02-01 08:12:08 +00005339 if (NewVD->hasAttrs())
5340 CheckAlignasUnderalignment(NewVD);
5341
Peter Collingbournec0c00662012-08-28 20:37:50 +00005342 if (getLangOpts().CUDA) {
5343 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5344 // storage [duration]."
5345 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola0db661e2012-12-21 01:21:33 +00005346 (NewVD->hasAttr<CUDASharedAttr>() ||
5347 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec0c00662012-08-28 20:37:50 +00005348 NewVD->setStorageClass(SC_Static);
Rafael Espindola0db661e2012-12-21 01:21:33 +00005349 }
Peter Collingbournec0c00662012-08-28 20:37:50 +00005350 }
5351
John McCallf85e1932011-06-15 23:02:42 +00005352 // In auto-retain/release, infer strong retension for variables of
5353 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00005354 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCallf85e1932011-06-15 23:02:42 +00005355 NewVD->setInvalidDecl();
5356
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005357 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner16c5dea2010-10-10 18:16:20 +00005358 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005359 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00005360 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner5f9e2722011-07-23 10:55:15 +00005361 StringRef Label = SE->getString();
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005362 if (S->getFnParent() != 0) {
5363 switch (SC) {
5364 case SC_None:
5365 case SC_Auto:
5366 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5367 break;
5368 case SC_Register:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00005369 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005370 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5371 break;
5372 case SC_Static:
5373 case SC_Extern:
5374 case SC_PrivateExtern:
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005375 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005376 break;
5377 }
5378 }
5379
5380 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindolabaf86952011-01-01 21:47:03 +00005381 Context, Label));
David Chisnall5f3c1632012-02-18 16:12:34 +00005382 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5383 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5384 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5385 if (I != ExtnameUndeclaredIdentifiers.end()) {
5386 NewVD->addAttr(I->second);
5387 ExtnameUndeclaredIdentifiers.erase(I);
5388 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005389 }
5390
John McCall8472af42010-03-16 21:48:18 +00005391 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00005392 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00005393 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00005394
John McCall68263142009-11-18 22:49:29 +00005395 // Don't consider existing declarations that are in a different
5396 // scope and are out-of-semantic-context declarations (if the new
5397 // declaration has linkage).
Larisse Voufoef4579c2013-08-06 01:03:05 +00005398 FilterLookupForScope(
Richard Smitha41c97a2013-09-20 01:15:31 +00005399 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
Larisse Voufoef4579c2013-08-06 01:03:05 +00005400 IsExplicitSpecialization || IsVariableTemplateSpecialization);
5401
Richard Smithdd9459f2013-08-13 18:18:50 +00005402 // Check whether the previous declaration is in the same block scope. This
5403 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5404 if (getLangOpts().CPlusPlus &&
5405 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5406 NewVD->setPreviousDeclInSameBlockScope(
5407 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00005408 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smithdd9459f2013-08-13 18:18:50 +00005409
David Blaikie4e4d0842012-03-11 07:00:24 +00005410 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005411 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5412 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005413 // Merge the decl with the existing one if appropriate.
5414 if (!Previous.empty()) {
5415 if (Previous.isSingleResult() &&
5416 isa<FieldDecl>(Previous.getFoundDecl()) &&
5417 D.getCXXScopeSpec().isSet()) {
5418 // The user tried to define a non-static data member
5419 // out-of-line (C++ [dcl.meaning]p1).
5420 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5421 << D.getCXXScopeSpec().getRange();
5422 Previous.clear();
5423 NewVD->setInvalidDecl();
5424 }
5425 } else if (D.getCXXScopeSpec().isSet()) {
5426 // No previous declaration in the qualifying scope.
5427 Diag(D.getIdentifierLoc(), diag::err_no_member)
5428 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005429 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005430 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005431 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005432
Larisse Voufoef4579c2013-08-06 01:03:05 +00005433 if (!IsVariableTemplateSpecialization) {
5434 if (PrevVarTemplate) {
5435 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5436 LookupOrdinaryName, ForRedeclaration);
5437 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo567f9172013-08-22 00:59:14 +00005438 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005439 } else
Larisse Voufo567f9172013-08-22 00:59:14 +00005440 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005441 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005442
5443 // This is an explicit specialization of a static data member. Check it.
Larisse Voufoef4579c2013-08-06 01:03:05 +00005444 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005445 CheckMemberSpecialization(NewVD, Previous))
5446 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005447 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00005448
Rafael Espindola65611bf2013-03-02 21:41:48 +00005449 ProcessPragmaWeak(S, NewVD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00005450 checkAttributesAfterMerging(*this, *NewVD);
5451
Richard Smithaa4bc182013-06-30 09:48:50 +00005452 // If this is the first declaration of an extern C variable, update
5453 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00005454 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00005455 isIncompleteDeclExternC(*this, NewVD))
Richard Smith662f41b2013-06-18 20:15:12 +00005456 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005457
Reid Kleckner942f9fe2013-09-10 20:14:30 +00005458 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman5e867c82013-07-10 00:30:46 +00005459 Decl *ManglingContextDecl;
5460 if (MangleNumberingContext *MCtx =
5461 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5462 ManglingContextDecl)) {
5463 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5464 }
5465 }
5466
Larisse Voufoef4579c2013-08-06 01:03:05 +00005467 // If we are providing an explicit specialization of a static variable
5468 // template, make a note of that.
5469 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo04592e72013-08-22 00:28:27 +00005470 PrevVarTemplate->setMemberSpecialization();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005471
Larisse Voufo567f9172013-08-22 00:59:14 +00005472 if (NewTemplate) {
5473 ActOnDocumentableDecl(NewTemplate);
5474 return NewTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005475 }
5476
Larisse Voufo567f9172013-08-22 00:59:14 +00005477 return NewVD;
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005478}
5479
John McCall053f4bd2010-03-22 09:20:08 +00005480/// \brief Diagnose variable or built-in function shadowing. Implements
5481/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00005482///
John McCall053f4bd2010-03-22 09:20:08 +00005483/// This method is called whenever a VarDecl is added to a "useful"
5484/// scope.
John McCall8472af42010-03-16 21:48:18 +00005485///
John McCalla369a952010-03-20 04:12:52 +00005486/// \param S the scope in which the shadowing name is being declared
5487/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00005488///
John McCall053f4bd2010-03-22 09:20:08 +00005489void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00005490 // Return if warning is ignored.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005491 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005492 DiagnosticsEngine::Ignored)
John McCall8472af42010-03-16 21:48:18 +00005493 return;
5494
Argyrios Kyrtzidis651f86f2011-02-08 18:21:25 +00005495 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005496 if (D->hasGlobalStorage())
John McCall8472af42010-03-16 21:48:18 +00005497 return;
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005498
5499 DeclContext *NewDC = D->getDeclContext();
5500
John McCalla369a952010-03-20 04:12:52 +00005501 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00005502 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00005503 return;
John McCall8472af42010-03-16 21:48:18 +00005504
John McCall8472af42010-03-16 21:48:18 +00005505 NamedDecl* ShadowedDecl = R.getFoundDecl();
5506 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5507 return;
5508
Argyrios Kyrtzidis36eb5e42011-01-31 07:04:54 +00005509 // Fields are not shadowed by variables in C++ static methods.
5510 if (isa<FieldDecl>(ShadowedDecl))
5511 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5512 if (MD->isStatic())
5513 return;
5514
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005515 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5516 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005517 // For shadowing external vars, make sure that we point to the global
5518 // declaration, not a locally scoped extern declaration.
5519 for (VarDecl::redecl_iterator
5520 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5521 I != E; ++I)
5522 if (I->isFileVarDecl()) {
5523 ShadowedDecl = *I;
5524 break;
5525 }
5526 }
5527
5528 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5529
John McCalla369a952010-03-20 04:12:52 +00005530 // Only warn about certain kinds of shadowing for class members.
5531 if (NewDC && NewDC->isRecord()) {
5532 // In particular, don't warn about shadowing non-class members.
5533 if (!OldDC->isRecord())
5534 return;
5535
5536 // TODO: should we warn about static data members shadowing
5537 // static data members from base classes?
5538
5539 // TODO: don't diagnose for inaccessible shadowed members.
5540 // This is hard to do perfectly because we might friend the
5541 // shadowing context, but that's just a false negative.
5542 }
5543
5544 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00005545 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00005546 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00005547 if (isa<FieldDecl>(ShadowedDecl))
5548 Kind = 3; // field
5549 else
5550 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00005551 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00005552 Kind = 1; // global
5553 else
5554 Kind = 0; // local
5555
John McCalla369a952010-03-20 04:12:52 +00005556 DeclarationName Name = R.getLookupName();
5557
John McCall8472af42010-03-16 21:48:18 +00005558 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00005559 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00005560 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5561}
5562
John McCall053f4bd2010-03-22 09:20:08 +00005563/// \brief Check -Wshadow without the advantage of a previous lookup.
5564void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005565 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005566 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005567 return;
5568
John McCall053f4bd2010-03-22 09:20:08 +00005569 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5570 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5571 LookupName(R, S);
5572 CheckShadow(S, D, R);
5573}
5574
Richard Smithaa4bc182013-06-30 09:48:50 +00005575/// Check for conflict between this global or extern "C" declaration and
5576/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola294ddc62013-01-11 19:34:23 +00005577template<typename T>
Richard Smithaa4bc182013-06-30 09:48:50 +00005578static bool checkGlobalOrExternCConflict(
5579 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5580 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5581 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005582
Richard Smithaa4bc182013-06-30 09:48:50 +00005583 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5584 // The common case: this global doesn't conflict with any extern "C"
5585 // declaration.
5586 return false;
5587 }
5588
5589 if (Prev) {
5590 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5591 // Both the old and new declarations have C language linkage. This is a
5592 // redeclaration.
5593 Previous.clear();
5594 Previous.addDecl(Prev);
5595 return true;
5596 }
5597
5598 // This is a global, non-extern "C" declaration, and there is a previous
5599 // non-global extern "C" declaration. Diagnose if this is a variable
5600 // declaration.
5601 if (!isa<VarDecl>(ND))
5602 return false;
5603 } else {
5604 // The declaration is extern "C". Check for any declaration in the
5605 // translation unit which might conflict.
5606 if (IsGlobal) {
5607 // We have already performed the lookup into the translation unit.
5608 IsGlobal = false;
5609 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5610 I != E; ++I) {
5611 if (isa<VarDecl>(*I)) {
5612 Prev = *I;
5613 break;
5614 }
5615 }
5616 } else {
5617 DeclContext::lookup_result R =
5618 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5619 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5620 I != E; ++I) {
5621 if (isa<VarDecl>(*I)) {
5622 Prev = *I;
5623 break;
5624 }
5625 // FIXME: If we have any other entity with this name in global scope,
5626 // the declaration is ill-formed, but that is a defect: it breaks the
5627 // 'stat' hack, for instance. Only variables can have mangled name
5628 // clashes with extern "C" declarations, so only they deserve a
5629 // diagnostic.
5630 }
5631 }
5632
5633 if (!Prev)
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005634 return false;
5635 }
5636
Richard Smithaa4bc182013-06-30 09:48:50 +00005637 // Use the first declaration's location to ensure we point at something which
5638 // is lexically inside an extern "C" linkage-spec.
5639 assert(Prev && "should have found a previous declaration to diagnose");
5640 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindolabc650912013-10-17 15:37:26 +00005641 Prev = FD->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005642 else
Rafael Espindolabc650912013-10-17 15:37:26 +00005643 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005644
5645 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5646 << IsGlobal << ND;
5647 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5648 << IsGlobal;
5649 return false;
5650}
5651
5652/// Apply special rules for handling extern "C" declarations. Returns \c true
5653/// if we have found that this is a redeclaration of some prior entity.
5654///
5655/// Per C++ [dcl.link]p6:
5656/// Two declarations [for a function or variable] with C language linkage
5657/// with the same name that appear in different scopes refer to the same
5658/// [entity]. An entity with C language linkage shall not be declared with
5659/// the same name as an entity in global scope.
5660template<typename T>
5661static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5662 LookupResult &Previous) {
5663 if (!S.getLangOpts().CPlusPlus) {
5664 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smitha41c97a2013-09-20 01:15:31 +00005665 // variable declared in function scope. We don't need this in C++, because
5666 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithaa4bc182013-06-30 09:48:50 +00005667 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5668 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5669 Previous.clear();
5670 Previous.addDecl(Prev);
5671 return true;
5672 }
5673 }
5674 return false;
5675 }
5676
5677 // A declaration in the translation unit can conflict with an extern "C"
5678 // declaration.
5679 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5680 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5681
5682 // An extern "C" declaration can conflict with a declaration in the
5683 // translation unit or can be a redeclaration of an extern "C" declaration
5684 // in another scope.
5685 if (isIncompleteDeclExternC(S,ND))
5686 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5687
5688 // Neither global nor extern "C": nothing to do.
5689 return false;
Rafael Espindola294ddc62013-01-11 19:34:23 +00005690}
5691
Richard Smithdc7a4f52013-04-30 13:56:41 +00005692void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00005693 // If the decl is already known invalid, don't check it.
5694 if (NewVD->isInvalidDecl())
Richard Smithdc7a4f52013-04-30 13:56:41 +00005695 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005696
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005697 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5698 QualType T = TInfo->getType();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005699
Richard Smithdc7a4f52013-04-30 13:56:41 +00005700 // Defer checking an 'auto' type until its initializer is attached.
5701 if (T->isUndeducedType())
5702 return;
5703
John McCallc12c5bb2010-05-15 11:32:37 +00005704 if (T->isObjCObjectType()) {
Fariborz Jahaniandcf10112011-07-25 21:12:27 +00005705 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5706 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00005707 T = Context.getObjCObjectPointerType(T);
5708 NewVD->setType(T);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005709 }
Mike Stump1eb44332009-09-09 15:08:12 +00005710
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005711 // Emit an error if an address space was applied to decl with local storage.
5712 // This includes arrays of objects with address space qualifiers, but not
5713 // automatic variables that point to other address spaces.
5714 // ISO/IEC TR 18037 S5.1.2
Chris Lattner16c5dea2010-10-10 18:16:20 +00005715 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005716 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005717 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005718 return;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005719 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00005720
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005721 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5722 // __constant address space.
5723 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5724 && T.getAddressSpace() != LangAS::opencl_constant
5725 && !T->isSamplerT()){
5726 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5727 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005728 return;
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005729 }
5730
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005731 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5732 // scope.
5733 if ((getLangOpts().OpenCLVersion >= 120)
5734 && NewVD->isStaticLocal()) {
5735 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5736 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005737 return;
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005738 }
5739
Mike Stumpf33651c2009-04-14 00:57:29 +00005740 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanian175df892011-06-07 20:15:46 +00005741 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005742 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanian175df892011-06-07 20:15:46 +00005743 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005744 else {
5745 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanian175df892011-06-07 20:15:46 +00005746 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005747 }
Fariborz Jahanian175df892011-06-07 20:15:46 +00005748 }
Chris Lattner16c5dea2010-10-10 18:16:20 +00005749
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005750 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00005751 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00005752 NewVD->hasAttr<BlocksAttr>())
John McCall781472f2010-08-25 08:40:02 +00005753 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00005754
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005755 if ((isVM && NewVD->hasLinkage()) ||
5756 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005757 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00005758 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005759 TypeSourceInfo *FixedTInfo =
5760 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5761 SizeIsNegative, Oversized);
5762 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005763 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00005764 // FIXME: This won't give the correct result for
5765 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005766 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005767
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005768 if (NewVD->isFileVarDecl())
5769 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005770 << SizeRange;
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005771 else if (NewVD->isStaticLocal())
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005772 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005773 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005774 else
5775 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005776 << SizeRange;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005777 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005778 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005779 }
5780
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005781 if (FixedTInfo == 0) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005782 if (NewVD->isFileVarDecl())
5783 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5784 else
5785 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005786 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005787 return;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005788 }
Mike Stump1eb44332009-09-09 15:08:12 +00005789
Chris Lattnereaaebc72009-04-25 08:06:05 +00005790 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnaraeae859a2012-11-08 16:01:51 +00005791 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005792 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005793 }
5794
David Majnemeraa715672013-05-29 00:56:45 +00005795 if (T->isVoidType()) {
5796 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5797 // of objects and functions.
5798 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5799 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5800 << T;
5801 NewVD->setInvalidDecl();
5802 return;
5803 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00005804 }
5805
5806 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5807 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5808 NewVD->setInvalidDecl();
5809 return;
5810 }
5811
5812 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5813 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5814 NewVD->setInvalidDecl();
5815 return;
5816 }
5817
5818 if (NewVD->isConstexpr() && !T->isDependentType() &&
5819 RequireLiteralType(NewVD->getLocation(), T,
5820 diag::err_constexpr_var_non_literal)) {
5821 // Can't perform this check until the type is deduced.
5822 NewVD->setInvalidDecl();
5823 return;
5824 }
5825}
5826
5827/// \brief Perform semantic checking on a newly-created variable
5828/// declaration.
5829///
5830/// This routine performs all of the type-checking required for a
5831/// variable declaration once it has been built. It is used both to
5832/// check variables after they have been parsed and their declarators
5833/// have been translated into a declaration, and to check variables
5834/// that have been instantiated from a template.
5835///
5836/// Sets NewVD->isInvalidDecl() if an error was encountered.
5837///
5838/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo567f9172013-08-22 00:59:14 +00005839bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00005840 CheckVariableDeclarationType(NewVD);
5841
5842 // If the decl is already known invalid, don't check it.
5843 if (NewVD->isInvalidDecl())
5844 return false;
5845
John McCall5b8740f2013-04-01 18:34:28 +00005846 // If we did not find anything by this name, look for a non-visible
5847 // extern "C" declaration with the same name.
Richard Smithdd9459f2013-08-13 18:18:50 +00005848 if (Previous.empty() &&
5849 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith99a72382013-09-03 21:00:58 +00005850 Previous.setShadowed();
Douglas Gregor63935192009-03-02 00:19:53 +00005851
Douglas Gregor7dc80e12013-01-09 00:47:56 +00005852 // Filter out any non-conflicting previous declarations.
5853 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5854
John McCall68263142009-11-18 22:49:29 +00005855 if (!Previous.empty()) {
Richard Smith99a72382013-09-03 21:00:58 +00005856 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005857 return true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005858 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005859 return false;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005860}
5861
Douglas Gregora8f32e02009-10-06 17:59:45 +00005862/// \brief Data used with FindOverriddenMethod
5863struct FindOverriddenMethodData {
5864 Sema *S;
5865 CXXMethodDecl *Method;
5866};
5867
5868/// \brief Member lookup function that determines whether a given C++
5869/// method overrides a method in a base class, to be used with
5870/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00005871static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00005872 CXXBasePath &Path,
5873 void *UserData) {
5874 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00005875
Douglas Gregora8f32e02009-10-06 17:59:45 +00005876 FindOverriddenMethodData *Data
5877 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00005878
5879 DeclarationName Name = Data->Method->getDeclName();
5880
5881 // FIXME: Do we care about other names here too?
5882 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00005883 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00005884 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5885 CanQualType CT = Data->S->Context.getCanonicalType(T);
5886
Anders Carlsson1a689722009-11-27 01:26:58 +00005887 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00005888 }
5889
5890 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005891 !Path.Decls.empty();
5892 Path.Decls = Path.Decls.slice(1)) {
5893 NamedDecl *D = Path.Decls.front();
John McCallad00b772010-06-16 08:42:20 +00005894 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5895 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00005896 return true;
5897 }
5898 }
5899
5900 return false;
5901}
5902
David Blaikie5708c182012-10-17 00:47:58 +00005903namespace {
5904 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5905}
5906/// \brief Report an error regarding overriding, along with any relevant
5907/// overriden methods.
5908///
5909/// \param DiagID the primary error to report.
5910/// \param MD the overriding method.
5911/// \param OEK which overrides to include as notes.
5912static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5913 OverrideErrorKind OEK = OEK_All) {
5914 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5915 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5916 E = MD->end_overridden_methods();
5917 I != E; ++I) {
5918 // This check (& the OEK parameter) could be replaced by a predicate, but
5919 // without lambdas that would be overkill. This is still nicer than writing
5920 // out the diag loop 3 times.
5921 if ((OEK == OEK_All) ||
5922 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5923 (OEK == OEK_Deleted && (*I)->isDeleted()))
5924 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5925 }
5926}
5927
Sebastian Redla165da02009-11-18 21:51:29 +00005928/// AddOverriddenMethods - See if a method overrides any in the base classes,
5929/// and if so, check that it's a valid override and remember it.
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005930bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redla165da02009-11-18 21:51:29 +00005931 // Look for virtual methods in base classes that this method might override.
5932 CXXBasePaths Paths;
5933 FindOverriddenMethodData Data;
5934 Data.Method = MD;
5935 Data.S = this;
David Blaikie5708c182012-10-17 00:47:58 +00005936 bool hasDeletedOverridenMethods = false;
5937 bool hasNonDeletedOverridenMethods = false;
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005938 bool AddedAny = false;
Sebastian Redla165da02009-11-18 21:51:29 +00005939 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5940 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5941 E = Paths.found_decls_end(); I != E; ++I) {
5942 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu304e2332011-07-01 20:02:53 +00005943 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00005944 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballmanfff32482012-12-09 17:45:41 +00005945 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithb9d0b762012-07-27 04:22:15 +00005946 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson2e1c7302011-01-20 16:25:36 +00005947 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie5708c182012-10-17 00:47:58 +00005948 hasDeletedOverridenMethods |= OldMD->isDeleted();
5949 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005950 AddedAny = true;
5951 }
Sebastian Redla165da02009-11-18 21:51:29 +00005952 }
5953 }
5954 }
David Blaikie5708c182012-10-17 00:47:58 +00005955
5956 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5957 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5958 }
5959 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5960 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5961 }
5962
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005963 return AddedAny;
Sebastian Redla165da02009-11-18 21:51:29 +00005964}
5965
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005966namespace {
5967 // Struct for holding all of the extra arguments needed by
5968 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5969 struct ActOnFDArgs {
5970 Scope *S;
5971 Declarator &D;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005972 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005973 bool AddToScope;
5974 };
5975}
5976
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005977namespace {
5978
5979// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005980// Also only accept corrections that have the same parent decl.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005981class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5982 public:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005983 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5984 CXXRecordDecl *Parent)
5985 : Context(Context), OriginalFD(TypoFD),
5986 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005987
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005988 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005989 if (candidate.getEditDistance() == 0)
5990 return false;
5991
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005992 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005993 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5994 CDeclEnd = candidate.end();
5995 CDecl != CDeclEnd; ++CDecl) {
5996 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5997
5998 if (FD && !FD->hasBody() &&
5999 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6000 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6001 CXXRecordDecl *Parent = MD->getParent();
6002 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6003 return true;
6004 } else if (!ExpectedParent) {
6005 return true;
6006 }
6007 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006008 }
6009
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006010 return false;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006011 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006012
6013 private:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006014 ASTContext &Context;
6015 FunctionDecl *OriginalFD;
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006016 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006017};
6018
6019}
6020
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006021/// \brief Generate diagnostics for an invalid function redeclaration.
6022///
6023/// This routine handles generating the diagnostic messages for an invalid
6024/// function redeclaration, including finding possible similar declarations
6025/// or performing typo correction if there are no previous declarations with
6026/// the same name.
6027///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006028/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006029/// the new declaration name does not cause new errors.
Richard Smith4e9686b2013-08-09 04:35:01 +00006030static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006031 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith4e9686b2013-08-09 04:35:01 +00006032 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006033 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006034 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006035 SmallVector<unsigned, 1> MismatchedParams;
6036 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006037 TypoCorrection Correction;
Richard Smith2d670972013-08-17 00:46:16 +00006038 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith4e9686b2013-08-09 04:35:01 +00006039 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6040 : diag::err_member_decl_does_not_match;
6041 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6042 IsLocalFriend ? Sema::LookupLocalFriendName
6043 : Sema::LookupOrdinaryName,
6044 Sema::ForRedeclaration);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006045
6046 NewFD->setInvalidDecl();
Richard Smith4e9686b2013-08-09 04:35:01 +00006047 if (IsLocalFriend)
6048 SemaRef.LookupName(Prev, S);
6049 else
6050 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCall29ae6e52010-10-13 05:45:15 +00006051 assert(!Prev.isAmbiguous() &&
6052 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006053 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006054 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6055 MD ? MD->getParent() : 0);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006056 if (!Prev.empty()) {
6057 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6058 Func != FuncEnd; ++Func) {
6059 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006060 if (FD &&
6061 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006062 // Add 1 to the index so that 0 can mean the mismatch didn't
6063 // involve a parameter
6064 unsigned ParamNum =
6065 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6066 NearMatches.push_back(std::make_pair(FD, ParamNum));
6067 }
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00006068 }
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006069 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith4e9686b2013-08-09 04:35:01 +00006070 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smith2d670972013-08-17 00:46:16 +00006071 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6072 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6073 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006074 // Set up everything for the call to ActOnFunctionDeclarator
6075 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6076 ExtraArgs.D.getIdentifierLoc());
6077 Previous.clear();
6078 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006079 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6080 CDeclEnd = Correction.end();
6081 CDecl != CDeclEnd; ++CDecl) {
6082 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006083 if (FD && !FD->hasBody() &&
6084 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006085 Previous.addDecl(FD);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006086 }
6087 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006088 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smith2d670972013-08-17 00:46:16 +00006089
6090 NamedDecl *Result;
6091 // Retry building the function declaration with the new previous
6092 // declarations, and with errors suppressed.
6093 {
6094 // Trap errors.
6095 Sema::SFINAETrap Trap(SemaRef);
6096
6097 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6098 // pieces need to verify the typo-corrected C++ declaration and hopefully
6099 // eliminate the need for the parameter pack ExtraArgs.
6100 Result = SemaRef.ActOnFunctionDeclarator(
6101 ExtraArgs.S, ExtraArgs.D,
6102 Correction.getCorrectionDecl()->getDeclContext(),
6103 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6104 ExtraArgs.AddToScope);
6105
6106 if (Trap.hasErrorOccurred())
6107 Result = 0;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006108 }
Richard Smith2d670972013-08-17 00:46:16 +00006109
6110 if (Result) {
6111 // Determine which correction we picked.
6112 Decl *Canonical = Result->getCanonicalDecl();
6113 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6114 I != E; ++I)
6115 if ((*I)->getCanonicalDecl() == Canonical)
6116 Correction.setCorrectionDecl(*I);
6117
6118 SemaRef.diagnoseTypo(
6119 Correction,
6120 SemaRef.PDiag(IsLocalFriend
6121 ? diag::err_no_matching_local_friend_suggest
6122 : diag::err_member_decl_does_not_match_suggest)
6123 << Name << NewDC << IsDefinition);
6124 return Result;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006125 }
Richard Smith2d670972013-08-17 00:46:16 +00006126
6127 // Pretend the typo correction never occurred
6128 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6129 ExtraArgs.D.getIdentifierLoc());
6130 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6131 Previous.clear();
6132 Previous.setLookupName(Name);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006133 }
6134
Richard Smith2d670972013-08-17 00:46:16 +00006135 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6136 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006137
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006138 bool NewFDisConst = false;
6139 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikie4ef832f2012-08-10 00:55:35 +00006140 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006141
Craig Topper8bc99dd2013-07-04 03:15:42 +00006142 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006143 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6144 NearMatch != NearMatchEnd; ++NearMatch) {
6145 FunctionDecl *FD = NearMatch->first;
Richard Smith4e9686b2013-08-09 04:35:01 +00006146 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6147 bool FDisConst = MD && MD->isConst();
6148 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006149
Richard Smitha41c97a2013-09-20 01:15:31 +00006150 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006151 if (unsigned Idx = NearMatch->second) {
6152 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smith1c931be2012-04-02 18:40:40 +00006153 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6154 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith4e9686b2013-08-09 04:35:01 +00006155 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6156 : diag::note_local_decl_close_param_match)
6157 << Idx << FDParam->getType()
6158 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006159 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006160 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006161 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006162 } else
Richard Smith4e9686b2013-08-09 04:35:01 +00006163 SemaRef.Diag(FD->getLocation(),
6164 IsMember ? diag::note_member_def_close_match
6165 : diag::note_local_decl_close_match);
John McCall29ae6e52010-10-13 05:45:15 +00006166 }
Richard Smith2d670972013-08-17 00:46:16 +00006167 return 0;
John McCall29ae6e52010-10-13 05:45:15 +00006168}
6169
David Blaikied662a792011-10-19 22:56:21 +00006170static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6171 Declarator &D) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006172 switch (D.getDeclSpec().getStorageClassSpec()) {
6173 default: llvm_unreachable("Unknown storage class!");
6174 case DeclSpec::SCS_auto:
6175 case DeclSpec::SCS_register:
6176 case DeclSpec::SCS_mutable:
6177 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6178 diag::err_typecheck_sclass_func);
6179 D.setInvalidType();
6180 break;
6181 case DeclSpec::SCS_unspecified: break;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00006182 case DeclSpec::SCS_extern:
6183 if (D.getDeclSpec().isExternInLinkageSpec())
6184 return SC_None;
6185 return SC_Extern;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006186 case DeclSpec::SCS_static: {
6187 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6188 // C99 6.7.1p5:
6189 // The declaration of an identifier for a function that has
6190 // block scope shall have no explicit storage-class specifier
6191 // other than extern
6192 // See also (C++ [dcl.stc]p4).
6193 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6194 diag::err_static_block_func);
6195 break;
6196 } else
6197 return SC_Static;
6198 }
6199 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6200 }
6201
6202 // No explicit storage class has already been returned
6203 return SC_None;
6204}
6205
6206static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6207 DeclContext *DC, QualType &R,
6208 TypeSourceInfo *TInfo,
6209 FunctionDecl::StorageClass SC,
6210 bool &IsVirtualOkay) {
6211 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6212 DeclarationName Name = NameInfo.getName();
6213
6214 FunctionDecl *NewFD = 0;
6215 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006216
David Blaikie4e4d0842012-03-11 07:00:24 +00006217 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006218 // Determine whether the function was written with a
6219 // prototype. This true when:
6220 // - there is a prototype in the declarator, or
6221 // - the type R of the function is some kind of typedef or other reference
6222 // to a type name (which eventually refers to a function type).
6223 bool HasPrototype =
6224 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6225 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6226
David Blaikied662a792011-10-19 22:56:21 +00006227 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006228 D.getLocStart(), NameInfo, R,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006229 TInfo, SC, isInline,
6230 HasPrototype, false);
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006231 if (D.isInvalidType())
6232 NewFD->setInvalidDecl();
6233
6234 // Set the lexical context.
6235 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6236
6237 return NewFD;
6238 }
6239
6240 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6241 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6242
6243 // Check that the return type is not an abstract class type.
6244 // For record types, this is done by the AbstractClassUsageDiagnoser once
6245 // the class has been completely parsed.
6246 if (!DC->isRecord() &&
6247 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6248 R->getAs<FunctionType>()->getResultType(),
6249 diag::err_abstract_type_in_decl,
6250 SemaRef.AbstractReturnType))
6251 D.setInvalidType();
6252
6253 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6254 // This is a C++ constructor declaration.
6255 assert(DC->isRecord() &&
6256 "Constructors can only be declared in a member context");
6257
6258 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6259 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006260 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006261 R, TInfo, isExplicit, isInline,
6262 /*isImplicitlyDeclared=*/false,
6263 isConstexpr);
6264
6265 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6266 // This is a C++ destructor declaration.
6267 if (DC->isRecord()) {
6268 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6269 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6270 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6271 SemaRef.Context, Record,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006272 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006273 NameInfo, R, TInfo, isInline,
6274 /*isImplicitlyDeclared=*/false);
6275
6276 // If the class is complete, then we now create the implicit exception
6277 // specification. If the class is incomplete or dependent, we can't do
6278 // it yet.
Richard Smith80ad52f2013-01-02 11:42:31 +00006279 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006280 Record->getDefinition() && !Record->isBeingDefined() &&
6281 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6282 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6283 }
6284
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006285 // The Microsoft ABI requires that we perform the destructor body
6286 // checks (i.e. operator delete() lookup) at every declaration, as
6287 // any translation unit may need to emit a deleting destructor.
6288 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6289 !Record->isDependentType() && Record->getDefinition() &&
6290 !Record->isBeingDefined()) {
6291 SemaRef.CheckDestructor(NewDD);
6292 }
6293
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006294 IsVirtualOkay = true;
6295 return NewDD;
6296
6297 } else {
6298 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6299 D.setInvalidType();
6300
6301 // Create a FunctionDecl to satisfy the function definition parsing
6302 // code path.
6303 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006304 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006305 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006306 SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006307 /*hasPrototype=*/true, isConstexpr);
6308 }
6309
6310 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6311 if (!DC->isRecord()) {
6312 SemaRef.Diag(D.getIdentifierLoc(),
6313 diag::err_conv_function_not_member);
6314 return 0;
6315 }
6316
6317 SemaRef.CheckConversionDeclarator(D, R, SC);
6318 IsVirtualOkay = true;
6319 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006320 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006321 R, TInfo, isInline, isExplicit,
6322 isConstexpr, SourceLocation());
6323
6324 } else if (DC->isRecord()) {
6325 // If the name of the function is the same as the name of the record,
6326 // then this must be an invalid constructor that has a return type.
6327 // (The parser checks for a return type and makes the declarator a
6328 // constructor if it has no return type).
6329 if (Name.getAsIdentifierInfo() &&
6330 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6331 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6332 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6333 << SourceRange(D.getIdentifierLoc());
6334 return 0;
6335 }
6336
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006337 // This is a C++ method declaration.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006338 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6339 cast<CXXRecordDecl>(DC),
6340 D.getLocStart(), NameInfo, R,
6341 TInfo, SC, isInline,
6342 isConstexpr, SourceLocation());
6343 IsVirtualOkay = !Ret->isStatic();
6344 return Ret;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006345 } else {
6346 // Determine whether the function was written with a
6347 // prototype. This true when:
6348 // - we're in C++ (where every function has a prototype),
6349 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006350 D.getLocStart(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006351 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006352 true/*HasPrototype*/, isConstexpr);
6353 }
6354}
6355
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006356void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6357 // In C++, the empty parameter-type-list must be spelled "void"; a
6358 // typedef of void is not permitted.
6359 if (getLangOpts().CPlusPlus &&
6360 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6361 bool IsTypeAlias = false;
6362 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6363 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6364 else if (const TemplateSpecializationType *TST =
6365 Param->getType()->getAs<TemplateSpecializationType>())
6366 IsTypeAlias = TST->isTypeAlias();
6367 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6368 << IsTypeAlias;
6369 }
6370}
6371
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00006372enum OpenCLParamType {
6373 ValidKernelParam,
6374 PtrPtrKernelParam,
6375 PtrKernelParam,
6376 InvalidKernelParam,
6377 RecordKernelParam
6378};
6379
6380static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6381 if (PT->isPointerType()) {
6382 QualType PointeeType = PT->getPointeeType();
6383 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6384 }
6385
6386 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6387 // be used as builtin types.
6388
6389 if (PT->isImageType())
6390 return PtrKernelParam;
6391
6392 if (PT->isBooleanType())
6393 return InvalidKernelParam;
6394
6395 if (PT->isEventT())
6396 return InvalidKernelParam;
6397
6398 if (PT->isHalfType())
6399 return InvalidKernelParam;
6400
6401 if (PT->isRecordType())
6402 return RecordKernelParam;
6403
6404 return ValidKernelParam;
6405}
6406
6407static void checkIsValidOpenCLKernelParameter(
6408 Sema &S,
6409 Declarator &D,
6410 ParmVarDecl *Param,
6411 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6412 QualType PT = Param->getType();
6413
6414 // Cache the valid types we encounter to avoid rechecking structs that are
6415 // used again
6416 if (ValidTypes.count(PT.getTypePtr()))
6417 return;
6418
6419 switch (getOpenCLKernelParameterType(PT)) {
6420 case PtrPtrKernelParam:
6421 // OpenCL v1.2 s6.9.a:
6422 // A kernel function argument cannot be declared as a
6423 // pointer to a pointer type.
6424 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6425 D.setInvalidType();
6426 return;
6427
6428 // OpenCL v1.2 s6.9.k:
6429 // Arguments to kernel functions in a program cannot be declared with the
6430 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6431 // uintptr_t or a struct and/or union that contain fields declared to be
6432 // one of these built-in scalar types.
6433
6434 case InvalidKernelParam:
6435 // OpenCL v1.2 s6.8 n:
6436 // A kernel function argument cannot be declared
6437 // of event_t type.
6438 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6439 D.setInvalidType();
6440 return;
6441
6442 case PtrKernelParam:
6443 case ValidKernelParam:
6444 ValidTypes.insert(PT.getTypePtr());
6445 return;
6446
6447 case RecordKernelParam:
6448 break;
6449 }
6450
6451 // Track nested structs we will inspect
6452 SmallVector<const Decl *, 4> VisitStack;
6453
6454 // Track where we are in the nested structs. Items will migrate from
6455 // VisitStack to HistoryStack as we do the DFS for bad field.
6456 SmallVector<const FieldDecl *, 4> HistoryStack;
6457 HistoryStack.push_back((const FieldDecl *) 0);
6458
6459 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6460 VisitStack.push_back(PD);
6461
6462 assert(VisitStack.back() && "First decl null?");
6463
6464 do {
6465 const Decl *Next = VisitStack.pop_back_val();
6466 if (!Next) {
6467 assert(!HistoryStack.empty());
6468 // Found a marker, we have gone up a level
6469 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6470 ValidTypes.insert(Hist->getType().getTypePtr());
6471
6472 continue;
6473 }
6474
6475 // Adds everything except the original parameter declaration (which is not a
6476 // field itself) to the history stack.
6477 const RecordDecl *RD;
6478 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6479 HistoryStack.push_back(Field);
6480 RD = Field->getType()->castAs<RecordType>()->getDecl();
6481 } else {
6482 RD = cast<RecordDecl>(Next);
6483 }
6484
6485 // Add a null marker so we know when we've gone back up a level
6486 VisitStack.push_back((const Decl *) 0);
6487
6488 for (RecordDecl::field_iterator I = RD->field_begin(),
6489 E = RD->field_end(); I != E; ++I) {
6490 const FieldDecl *FD = *I;
6491 QualType QT = FD->getType();
6492
6493 if (ValidTypes.count(QT.getTypePtr()))
6494 continue;
6495
6496 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6497 if (ParamType == ValidKernelParam)
6498 continue;
6499
6500 if (ParamType == RecordKernelParam) {
6501 VisitStack.push_back(FD);
6502 continue;
6503 }
6504
6505 // OpenCL v1.2 s6.9.p:
6506 // Arguments to kernel functions that are declared to be a struct or union
6507 // do not allow OpenCL objects to be passed as elements of the struct or
6508 // union.
6509 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6510 S.Diag(Param->getLocation(),
6511 diag::err_record_with_pointers_kernel_param)
6512 << PT->isUnionType()
6513 << PT;
6514 } else {
6515 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6516 }
6517
6518 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6519 << PD->getDeclName();
6520
6521 // We have an error, now let's go back up through history and show where
6522 // the offending field came from
6523 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6524 E = HistoryStack.end(); I != E; ++I) {
6525 const FieldDecl *OuterField = *I;
6526 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6527 << OuterField->getType();
6528 }
6529
6530 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6531 << QT->isPointerType()
6532 << QT;
6533 D.setInvalidType();
6534 return;
6535 }
6536 } while (!VisitStack.empty());
6537}
6538
Mike Stump1eb44332009-09-09 15:08:12 +00006539NamedDecl*
Nick Lewycky25af0912011-07-02 02:05:12 +00006540Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006541 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00006542 MultiTemplateParamsArg TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006543 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006544 QualType R = TInfo->getType();
6545
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006546 assert(R.getTypePtr()->isFunctionType());
6547
Abramo Bagnara25777432010-08-11 22:01:17 +00006548 // TODO: consider using NameInfo for diagnostic.
6549 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6550 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006551 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006552
Richard Smithec642442013-04-12 22:46:28 +00006553 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6554 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6555 diag::err_invalid_thread)
6556 << DeclSpec::getSpecifierName(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00006557
Reid Klecknerd1a32c32013-10-08 00:58:57 +00006558 if (D.isFirstDeclarationOfMember())
6559 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckneref072032013-08-27 23:08:25 +00006560
Douglas Gregor3922ed02010-12-10 19:28:19 +00006561 bool isFriend = false;
Douglas Gregor3922ed02010-12-10 19:28:19 +00006562 FunctionTemplateDecl *FunctionTemplate = 0;
6563 bool isExplicitSpecialization = false;
6564 bool isFunctionTemplateSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006565
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006566 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006567 bool HasExplicitTemplateArgs = false;
6568 TemplateArgumentListInfo TemplateArgs;
6569
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006570 bool isVirtualOkay = false;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006571
Richard Smitha41c97a2013-09-20 01:15:31 +00006572 DeclContext *OriginalDC = DC;
6573 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6574
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006575 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6576 isVirtualOkay);
6577 if (!NewFD) return 0;
6578
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00006579 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6580 NewFD->setTopLevelDeclInObjCContainer();
6581
Richard Smitha41c97a2013-09-20 01:15:31 +00006582 // Set the lexical context. If this is a function-scope declaration, or has a
6583 // C++ scope specifier, or is the object of a friend declaration, the lexical
6584 // context will be different from the semantic context.
6585 NewFD->setLexicalDeclContext(CurContext);
6586
6587 if (IsLocalExternDecl)
6588 NewFD->setLocalExternDecl();
6589
David Blaikie4e4d0842012-03-11 07:00:24 +00006590 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006591 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00006592 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6593 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006594 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006595 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006596 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnarab0a2fcc2011-03-18 15:21:59 +00006597 // C++ [class.friend]p5
6598 // A function can be defined in a friend declaration of a
6599 // class . . . . Such a function is implicitly inline.
6600 NewFD->setImplicitlyInline();
6601 }
6602
John McCalle402e722012-09-25 07:32:39 +00006603 // If this is a method defined in an __interface, and is not a constructor
6604 // or an overloaded operator, then set the pure flag (isVirtual will already
6605 // return true).
6606 if (const CXXRecordDecl *Parent =
6607 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6608 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matos6666ed42012-08-31 18:45:21 +00006609 NewFD->setPure(true);
6610 }
6611
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006612 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006613 isExplicitSpecialization = false;
6614 isFunctionTemplateSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006615 if (D.isInvalidType())
6616 NewFD->setInvalidDecl();
Richard Smitha41c97a2013-09-20 01:15:31 +00006617
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006618 // Match up the template parameter lists with the scope specifier, then
6619 // determine whether we have a template or a template specialization.
6620 bool Invalid = false;
Robert Wilhelm1169e2f2013-07-21 15:20:44 +00006621 if (TemplateParameterList *TemplateParams =
6622 MatchTemplateParametersToScopeSpecifier(
6623 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6624 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6625 isExplicitSpecialization, Invalid)) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006626 if (TemplateParams->size() > 0) {
6627 // This is a function template
Abramo Bagnara9b934882010-06-12 08:15:14 +00006628
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006629 // Check that we can declare a template here.
6630 if (CheckTemplateDeclScope(S, TemplateParams))
6631 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006632
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006633 // A destructor cannot be a template.
6634 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6635 Diag(NewFD->getLocation(), diag::err_destructor_template);
6636 return 0;
John McCall5fd378b2010-03-24 08:27:58 +00006637 }
Douglas Gregor20606502011-10-14 15:31:12 +00006638
6639 // If we're adding a template to a dependent context, we may need to
David Blaikied662a792011-10-19 22:56:21 +00006640 // rebuilding some of the types used within the template parameter list,
Douglas Gregor20606502011-10-14 15:31:12 +00006641 // now that we know what the current instantiation is.
6642 if (DC->isDependentContext()) {
6643 ContextRAII SavedContext(*this, DC);
6644 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6645 Invalid = true;
6646 }
6647
John McCall5fd378b2010-03-24 08:27:58 +00006648
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006649 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6650 NewFD->getLocation(),
6651 Name, TemplateParams,
6652 NewFD);
6653 FunctionTemplate->setLexicalDeclContext(CurContext);
6654 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6655
6656 // For source fidelity, store the other template param lists.
6657 if (TemplateParamLists.size() > 1) {
6658 NewFD->setTemplateParameterListsInfo(Context,
6659 TemplateParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00006660 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006661 }
6662 } else {
6663 // This is a function template specialization.
6664 isFunctionTemplateSpecialization = true;
6665 // For source fidelity, store all the template param lists.
6666 NewFD->setTemplateParameterListsInfo(Context,
6667 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006668 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006669
6670 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6671 if (isFriend) {
6672 // We want to remove the "template<>", found here.
6673 SourceRange RemoveRange = TemplateParams->getSourceRange();
6674
6675 // If we remove the template<> and the name is not a
6676 // template-id, we're actually silently creating a problem:
6677 // the friend declaration will refer to an untemplated decl,
6678 // and clearly the user wants a template specialization. So
6679 // we need to insert '<>' after the name.
6680 SourceLocation InsertLoc;
6681 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6682 InsertLoc = D.getName().getSourceRange().getEnd();
6683 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6684 }
6685
6686 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6687 << Name << RemoveRange
6688 << FixItHint::CreateRemoval(RemoveRange)
6689 << FixItHint::CreateInsertion(InsertLoc, "<>");
6690 }
6691 }
6692 }
6693 else {
6694 // All template param lists were matched against the scope specifier:
6695 // this is NOT (an explicit specialization of) a template.
6696 if (TemplateParamLists.size() > 0)
6697 // For source fidelity, store all the template param lists.
6698 NewFD->setTemplateParameterListsInfo(Context,
6699 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006700 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006701 }
6702
6703 if (Invalid) {
6704 NewFD->setInvalidDecl();
6705 if (FunctionTemplate)
6706 FunctionTemplate->setInvalidDecl();
6707 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006708
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006709 // C++ [dcl.fct.spec]p5:
6710 // The virtual specifier shall only be used in declarations of
6711 // nonstatic class member functions that appear within a
6712 // member-specification of a class declaration; see 10.3.
6713 //
6714 if (isVirtual && !NewFD->isInvalidDecl()) {
6715 if (!isVirtualOkay) {
6716 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6717 diag::err_virtual_non_function);
6718 } else if (!CurContext->isRecord()) {
6719 // 'virtual' was specified outside of the class.
Anders Carlssonf1602a52011-01-22 14:43:56 +00006720 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6721 diag::err_virtual_out_of_class)
6722 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6723 } else if (NewFD->getDescribedFunctionTemplate()) {
6724 // C++ [temp.mem]p3:
6725 // A member function template shall not be virtual.
6726 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6727 diag::err_virtual_member_function_template)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006728 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6729 } else {
6730 // Okay: Add virtual to the method.
6731 NewFD->setVirtualAsWritten(true);
John McCall7ad650f2010-03-24 07:46:06 +00006732 }
Richard Smith60e141e2013-05-04 07:00:32 +00006733
6734 if (getLangOpts().CPlusPlus1y &&
6735 NewFD->getResultType()->isUndeducedType())
6736 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00006737 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006738
Richard Smith37e849a2013-08-14 20:16:31 +00006739 if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() &&
6740 NewFD->getResultType()->isUndeducedType()) {
6741 // If the function template is referenced directly (for instance, as a
6742 // member of the current instantiation), pretend it has a dependent type.
6743 // This is not really justified by the standard, but is the only sane
6744 // thing to do.
6745 const FunctionProtoType *FPT =
6746 NewFD->getType()->castAs<FunctionProtoType>();
6747 QualType Result = SubstAutoType(FPT->getResultType(),
6748 Context.DependentTy);
6749 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6750 FPT->getExtProtoInfo()));
6751 }
6752
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006753 // C++ [dcl.fct.spec]p3:
David Blaikied662a792011-10-19 22:56:21 +00006754 // The inline specifier shall not appear on a block scope function
6755 // declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006756 if (isInline && !NewFD->isInvalidDecl()) {
6757 if (CurContext->isFunctionOrMethod()) {
6758 // 'inline' is not allowed on block scope function declaration.
6759 Diag(D.getDeclSpec().getInlineSpecLoc(),
6760 diag::err_inline_declaration_block_scope) << Name
6761 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6762 }
6763 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006764
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006765 // C++ [dcl.fct.spec]p6:
6766 // The explicit specifier shall be used only in the declaration of a
David Blaikied662a792011-10-19 22:56:21 +00006767 // constructor or conversion function within its class definition;
6768 // see 12.3.1 and 12.3.2.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006769 if (isExplicit && !NewFD->isInvalidDecl()) {
6770 if (!CurContext->isRecord()) {
6771 // 'explicit' was specified outside of the class.
6772 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6773 diag::err_explicit_out_of_class)
6774 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6775 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6776 !isa<CXXConversionDecl>(NewFD)) {
6777 // 'explicit' was specified on a function that wasn't a constructor
6778 // or conversion function.
6779 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6780 diag::err_explicit_non_ctor_or_conv_function)
6781 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6782 }
6783 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006784
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006785 if (isConstexpr) {
Richard Smith21c8fa82013-01-14 05:37:29 +00006786 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006787 // are implicitly inline.
6788 NewFD->setImplicitlyInline();
6789
Richard Smith21c8fa82013-01-14 05:37:29 +00006790 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006791 // be either constructors or to return a literal type. Therefore,
6792 // destructors cannot be declared constexpr.
6793 if (isa<CXXDestructorDecl>(NewFD))
Richard Smith9f569cc2011-10-01 02:31:28 +00006794 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006795 }
6796
Douglas Gregor8d267c52011-09-09 02:06:17 +00006797 // If __module_private__ was specified, mark the function accordingly.
6798 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00006799 if (isFunctionTemplateSpecialization) {
6800 SourceLocation ModulePrivateLoc
6801 = D.getDeclSpec().getModulePrivateSpecLoc();
6802 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6803 << 0
6804 << FixItHint::CreateRemoval(ModulePrivateLoc);
6805 } else {
6806 NewFD->setModulePrivate();
6807 if (FunctionTemplate)
6808 FunctionTemplate->setModulePrivate();
6809 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00006810 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006811
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006812 if (isFriend) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006813 if (FunctionTemplate) {
Richard Smith22050f22013-07-17 23:53:16 +00006814 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006815 FunctionTemplate->setAccess(AS_public);
6816 }
Richard Smith22050f22013-07-17 23:53:16 +00006817 NewFD->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006818 NewFD->setAccess(AS_public);
6819 }
6820
Douglas Gregor45fa5602011-11-07 20:56:01 +00006821 // If a function is defined as defaulted or deleted, mark it as such now.
6822 switch (D.getFunctionDefinitionKind()) {
6823 case FDK_Declaration:
6824 case FDK_Definition:
6825 break;
6826
6827 case FDK_Defaulted:
6828 NewFD->setDefaulted();
6829 break;
6830
6831 case FDK_Deleted:
6832 NewFD->setDeletedAsWritten();
6833 break;
6834 }
6835
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006836 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6837 D.isFunctionDefinition()) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00006838 // C++ [class.mfct]p2:
6839 // A member function may be defined (8.4) in its class definition, in
6840 // which case it is an inline member function (7.1.2)
John McCallbfdcdc82010-12-15 04:00:32 +00006841 NewFD->setImplicitlyInline();
6842 }
6843
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006844 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6845 !CurContext->isRecord()) {
6846 // C++ [class.static]p1:
6847 // A data or function member of a class may be declared static
6848 // in a class definition, in which case it is a static member of
6849 // the class.
6850
6851 // Complain about the 'static' specifier if it's on an out-of-line
6852 // member function definition.
6853 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6854 diag::err_static_out_of_line)
6855 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6856 }
Richard Smith444d3842012-10-20 08:26:51 +00006857
6858 // C++11 [except.spec]p15:
6859 // A deallocation function with no exception-specification is treated
6860 // as if it were specified with noexcept(true).
6861 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6862 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6863 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006864 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith444d3842012-10-20 08:26:51 +00006865 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6866 EPI.ExceptionSpecType = EST_BasicNoexcept;
6867 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00006868 FPT->getArgTypes(), EPI));
Richard Smith444d3842012-10-20 08:26:51 +00006869 }
David Majnemerd2b0cf32013-10-20 05:40:29 +00006870
6871 // C++11 [replacement.functions]p3:
6872 // The program's definitions shall not be specified as inline.
David Majnemer3abf5f62013-10-21 00:25:32 +00006873 //
6874 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
David Majnemerd2b0cf32013-10-20 05:40:29 +00006875 if (isInline && NewFD->isReplaceableGlobalAllocationFunction())
6876 Diag(D.getDeclSpec().getInlineSpecLoc(),
6877 diag::err_operator_new_delete_declared_inline)
6878 << NewFD->getDeclName();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00006879 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006880
6881 // Filter out previous declarations that don't match the scope.
Richard Smitha41c97a2013-09-20 01:15:31 +00006882 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006883 isExplicitSpecialization ||
6884 isFunctionTemplateSpecialization);
Richard Smithdd9459f2013-08-13 18:18:50 +00006885
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006886 // Handle GNU asm-label extension (encoded as an attribute).
6887 if (Expr *E = (Expr*) D.getAsmLabel()) {
6888 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00006889 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00006890 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6891 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00006892 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6893 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6894 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6895 if (I != ExtnameUndeclaredIdentifiers.end()) {
6896 NewFD->addAttr(I->second);
6897 ExtnameUndeclaredIdentifiers.erase(I);
6898 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006899 }
6900
Chris Lattner2dbd2852009-04-25 06:12:16 +00006901 // Copy the parameter declarations from the declarator D to the function
6902 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006903 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00006904 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006905 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006906
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006907 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6908 // function that takes no arguments, not a function that takes a
6909 // single void argument.
6910 // We let through "const void" here because Sema::GetTypeForDeclarator
6911 // already checks for that case.
6912 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6913 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006914 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00006915 // Empty arg list, don't push any params.
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006916 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006917 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006918 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00006919 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006920 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6921 Param->setDeclContext(NewFD);
6922 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00006923
6924 if (Param->isInvalidDecl())
6925 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006926 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006927 }
Mike Stump1eb44332009-09-09 15:08:12 +00006928
John McCall183700f2009-09-21 23:43:11 +00006929 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00006930 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006931 // following example, we'll need to synthesize (unnamed)
6932 // parameters for use in the declaration.
6933 //
6934 // @code
6935 // typedef void fn(int);
6936 // fn f;
6937 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00006938
Chris Lattner1ad9b282009-04-25 06:03:53 +00006939 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00006940 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6941 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00006942 ParmVarDecl *Param =
6943 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00006944 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00006945 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006946 }
Chris Lattner84bb9442009-04-25 18:38:18 +00006947 } else {
6948 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6949 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006950 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00006951
Chris Lattner2dbd2852009-04-25 06:12:16 +00006952 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00006953 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00006954
James Molloy16f1f712012-02-29 10:24:19 +00006955 // Find all anonymous symbols defined during the declaration of this function
6956 // and add to NewFD. This lets us track decls such 'enum Y' in:
6957 //
6958 // void f(enum Y {AA} x) {}
6959 //
6960 // which would otherwise incorrectly end up in the translation unit scope.
6961 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6962 DeclsInPrototypeScope.clear();
6963
Richard Smith7586a6e2013-01-30 05:45:05 +00006964 if (D.getDeclSpec().isNoreturnSpecified())
6965 NewFD->addAttr(
6966 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6967 Context));
6968
Richard Smithb03a9df2012-03-13 05:56:40 +00006969 // Functions returning a variably modified type violate C99 6.7.5.2p2
6970 // because all functions have linkage.
6971 if (!NewFD->isInvalidDecl() &&
6972 NewFD->getResultType()->isVariablyModifiedType()) {
6973 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6974 NewFD->setInvalidDecl();
6975 }
6976
Rafael Espindola98ae8342012-05-10 02:50:16 +00006977 // Handle attributes.
Richard Smith4a97b8e2013-08-29 00:47:48 +00006978 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindola98ae8342012-05-10 02:50:16 +00006979
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006980 QualType RetType = NewFD->getResultType();
6981 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6982 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6983 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6984 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006985 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramera32966f2013-10-16 16:21:04 +00006986 // Attach the attribute to the new decl. Don't apply the attribute if it
6987 // returns an instance of the class (e.g. assignment operators).
6988 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006989 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6990 Context));
6991 }
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006992 }
6993
David Blaikie4e4d0842012-03-11 07:00:24 +00006994 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006995 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00006996 bool isExplicitSpecialization=false;
David Majnemerc371db62013-07-06 02:13:46 +00006997 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6998 CheckMain(NewFD, D.getDeclSpec());
6999
David Majnemere9f6f332013-09-16 22:44:20 +00007000 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7001 CheckMSVCRTEntryPoint(NewFD);
7002
David Majnemerc371db62013-07-06 02:13:46 +00007003 if (!NewFD->isInvalidDecl())
Richard Smithb03a9df2012-03-13 05:56:40 +00007004 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7005 isExplicitSpecialization));
Fariborz Jahanian37c765a2012-09-05 17:52:12 +00007006 else if (!Previous.empty())
Richard Smithdd9459f2013-08-13 18:18:50 +00007007 // Make graceful recovery from an invalid redeclaration.
7008 D.setRedeclaration(true);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007009 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007010 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7011 "previous declaration set still overloaded");
7012 } else {
7013 // If the declarator is a template-id, translate the parser's template
7014 // argument list into our AST format.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007015 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7016 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7017 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7018 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00007019 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007020 TemplateId->NumArgs);
7021 translateTemplateArguments(TemplateArgsPtr,
7022 TemplateArgs);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007023
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007024 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007025
Douglas Gregor89b9f102011-06-06 15:22:55 +00007026 if (NewFD->isInvalidDecl()) {
7027 HasExplicitTemplateArgs = false;
7028 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00007029 // Function template with explicit template arguments.
7030 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7031 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7032
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007033 HasExplicitTemplateArgs = false;
7034 } else if (!isFunctionTemplateSpecialization &&
7035 !D.getDeclSpec().isFriendSpecified()) {
7036 // We have encountered something that the user meant to be a
7037 // specialization (because it has explicitly-specified template
7038 // arguments) but that was not introduced with a "template<>" (or had
7039 // too few of them).
Larisse Voufoef4579c2013-08-06 01:03:05 +00007040 // FIXME: Differentiate between attempts for explicit instantiations
7041 // (starting with "template") and the rest.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007042 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7043 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7044 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00007045 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00007046 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007047 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00007048 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007049 // "friend void foo<>(int);" is an implicit specialization decl.
7050 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00007051 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007052 } else if (isFriend && isFunctionTemplateSpecialization) {
7053 // This combination is only possible in a recovery case; the user
7054 // wrote something like:
7055 // template <> friend void foo(int);
7056 // which we're recovering from as if the user had written:
7057 // friend void foo<>(int);
7058 // Go ahead and fake up a template id.
7059 HasExplicitTemplateArgs = true;
7060 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7061 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007062 }
John McCall29ae6e52010-10-13 05:45:15 +00007063
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007064 // If it's a friend (and only if it's a friend), it's possible
7065 // that either the specialized function type or the specialized
7066 // template is dependent, and therefore matching will fail. In
7067 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007068 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007069 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007070 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7071 TemplateSpecializationType::anyDependentTemplateArguments(
7072 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7073 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007074 assert(HasExplicitTemplateArgs &&
7075 "friend function specialization without template args");
7076 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7077 Previous))
7078 NewFD->setInvalidDecl();
7079 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007080 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00007081 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007082 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00007083 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007084 diag::ext_function_specialization_in_class :
7085 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007086 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007087 } else if (CheckFunctionTemplateSpecialization(NewFD,
7088 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7089 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007090 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00007091
7092 // C++ [dcl.stc]p1:
7093 // A storage-class-specifier shall not be specified in an explicit
7094 // specialization (14.7.3)
Richard Trieu62ab0102013-05-16 02:14:08 +00007095 FunctionTemplateSpecializationInfo *Info =
7096 NewFD->getTemplateSpecializationInfo();
7097 if (Info && SC != SC_None) {
7098 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor0f9dc862011-06-17 05:09:08 +00007099 Diag(NewFD->getLocation(),
7100 diag::err_explicit_specialization_inconsistent_storage_class)
7101 << SC
7102 << FixItHint::CreateRemoval(
7103 D.getDeclSpec().getStorageClassSpecLoc());
7104
7105 else
7106 Diag(NewFD->getLocation(),
7107 diag::ext_explicit_specialization_storage_class)
7108 << FixItHint::CreateRemoval(
7109 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00007110 }
7111
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007112 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7113 if (CheckMemberSpecialization(NewFD, Previous))
7114 NewFD->setInvalidDecl();
7115 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007116
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007117 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00007118 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemerc371db62013-07-06 02:13:46 +00007119 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7120 CheckMain(NewFD, D.getDeclSpec());
7121
David Majnemere9f6f332013-09-16 22:44:20 +00007122 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7123 CheckMSVCRTEntryPoint(NewFD);
7124
David Blaikie14068e82011-09-08 06:33:04 +00007125 if (NewFD->isInvalidDecl()) {
7126 // If this is a class member, mark the class invalid immediately.
7127 // This avoids some consistency errors later.
7128 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7129 methodDecl->getParent()->setInvalidDecl();
David Majnemerc371db62013-07-06 02:13:46 +00007130 } else
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007131 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7132 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00007133 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007134
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007135 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007136 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7137 "previous declaration set still overloaded");
7138
7139 NamedDecl *PrincipalDecl = (FunctionTemplate
7140 ? cast<NamedDecl>(FunctionTemplate)
7141 : NewFD);
7142
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007143 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007144 AccessSpecifier Access = AS_public;
7145 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00007146 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007147
7148 NewFD->setAccess(Access);
7149 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007150 }
7151
7152 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7153 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7154 PrincipalDecl->setNonMemberOperator();
7155
7156 // If we have a function template, check the template parameter
7157 // list. This will check and merge default template arguments.
7158 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00007159 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00007160 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007161 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00007162 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00007163 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007164 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00007165 ? TPC_FriendFunctionTemplateDefinition
7166 : TPC_FriendFunctionTemplate)
7167 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00007168 DC && DC->isRecord() &&
7169 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00007170 ? TPC_ClassTemplateMember
7171 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007172 }
7173
7174 if (NewFD->isInvalidDecl()) {
7175 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007176 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00007177 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007178 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007179 // Fake up an access specifier if it's supposed to be a class member.
7180 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7181 NewFD->setAccess(AS_public);
7182
7183 // Qualified decls generally require a previous declaration.
7184 if (D.getCXXScopeSpec().isSet()) {
7185 // ...with the major exception of templated-scope or
7186 // dependent-scope friend declarations.
7187
7188 // TODO: we currently also suppress this check in dependent
7189 // contexts because (1) the parameter depth will be off when
7190 // matching friend templates and (2) we might actually be
7191 // selecting a friend based on a dependent factor. But there
7192 // are situations where these conditions don't apply and we
7193 // can actually do this check immediately.
7194 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007195 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007196 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7197 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007198 // ignore these
7199 } else {
7200 // The user tried to provide an out-of-line definition for a
7201 // function that is a member of a class or namespace, but there
7202 // was no such member function declared (C++ [class.mfct]p2,
7203 // C++ [namespace.memdef]p2). For example:
7204 //
7205 // class X {
7206 // void f() const;
7207 // };
7208 //
7209 // void X::f() { } // ill-formed
7210 //
7211 // Complain about this problem, and attempt to suggest close
7212 // matches (e.g., those that differ only in cv-qualifiers and
7213 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007214
Richard Smith4e9686b2013-08-09 04:35:01 +00007215 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7216 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007217 AddToScope = ExtraArgs.AddToScope;
7218 return Result;
7219 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007220 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007221
7222 // Unqualified local friend declarations are required to resolve
7223 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007224 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith4e9686b2013-08-09 04:35:01 +00007225 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7226 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007227 AddToScope = ExtraArgs.AddToScope;
7228 return Result;
7229 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007230 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007231
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007232 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007233 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00007234 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007235 // An out-of-line member function declaration must also be a
7236 // definition (C++ [dcl.meaning]p1).
7237 // Note that this is not the case for explicit specializations of
7238 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00007239 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7240 // extension for compatibility with old SWIG code which likes to
7241 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007242 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7243 << D.getCXXScopeSpec().getRange();
7244 }
7245 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00007246
Rafael Espindola65611bf2013-03-02 21:41:48 +00007247 ProcessPragmaWeak(S, NewFD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00007248 checkAttributesAfterMerging(*this, *NewFD);
7249
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007250 AddKnownFunctionAttributes(NewFD);
7251
Douglas Gregord9455382010-08-06 13:50:58 +00007252 if (NewFD->hasAttr<OverloadableAttr>() &&
7253 !NewFD->getType()->getAs<FunctionProtoType>()) {
7254 Diag(NewFD->getLocation(),
7255 diag::err_attribute_overloadable_no_prototype)
7256 << NewFD;
7257
7258 // Turn this into a variadic function with no parameters.
7259 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckneref072032013-08-27 23:08:25 +00007260 FunctionProtoType::ExtProtoInfo EPI(
7261 Context.getDefaultCallingConvention(true, false));
John McCalle23cf432010-12-14 08:05:40 +00007262 EPI.Variadic = true;
7263 EPI.ExtInfo = FT->getExtInfo();
7264
Dmitri Gribenko55431692013-05-05 00:41:58 +00007265 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00007266 NewFD->setType(R);
7267 }
7268
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007269 // If there's a #pragma GCC visibility in scope, and this isn't a class
7270 // member, set the visibility of this function.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007271 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007272 AddPushedVisibilityAttribute(NewFD);
7273
John McCall8dfac0b2011-09-30 05:12:12 +00007274 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7275 // marking the function.
7276 AddCFAuditedAttribute(NewFD);
7277
Richard Smithaa4bc182013-06-30 09:48:50 +00007278 // If this is the first declaration of an extern C variable, update
7279 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00007280 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00007281 isIncompleteDeclExternC(*this, NewFD))
Richard Smith662f41b2013-06-18 20:15:12 +00007282 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007283
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007284 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007285 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007286
David Blaikie4e4d0842012-03-11 07:00:24 +00007287 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007288 if (FunctionTemplate) {
7289 if (NewFD->isInvalidDecl())
7290 FunctionTemplate->setInvalidDecl();
7291 return FunctionTemplate;
7292 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007293 }
Mike Stump1eb44332009-09-09 15:08:12 +00007294
Guy Benyeie6b9d802013-01-20 12:31:11 +00007295 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyeie6b9d802013-01-20 12:31:11 +00007296 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7297 if ((getLangOpts().OpenCLVersion >= 120)
7298 && (SC == SC_Static)) {
7299 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7300 D.setInvalidType();
7301 }
Tanya Lattner7564bcc2013-01-30 19:48:52 +00007302
7303 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7304 if (!NewFD->getResultType()->isVoidType()) {
7305 Diag(D.getIdentifierLoc(),
7306 diag::err_expected_kernel_void_return_type);
7307 D.setInvalidType();
7308 }
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007309
7310 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007311 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7312 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly98f988d2013-01-29 10:54:06 +00007313 ParmVarDecl *Param = *PI;
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007314 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyeie6b9d802013-01-20 12:31:11 +00007315 }
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00007316 }
7317
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00007318 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007319
David Blaikie4e4d0842012-03-11 07:00:24 +00007320 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007321 if (IdentifierInfo *II = NewFD->getIdentifier())
7322 if (!NewFD->isInvalidDecl() &&
7323 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7324 if (II->isStr("cudaConfigureCall")) {
7325 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7326 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7327
7328 Context.setcudaConfigureCallDecl(NewFD);
7329 }
7330 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007331
7332 // Here we have an function template explicit specialization at class scope.
7333 // The actually specialization will be postponed to template instatiation
7334 // time via the ClassScopeFunctionSpecializationDecl node.
7335 if (isDependentClassScopeExplicitSpecialization) {
7336 ClassScopeFunctionSpecializationDecl *NewSpec =
7337 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber6b020092012-06-25 17:21:05 +00007338 Context, CurContext, SourceLocation(),
7339 cast<CXXMethodDecl>(NewFD),
7340 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007341 CurContext->addDecl(NewSpec);
7342 AddToScope = false;
7343 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007344
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007345 return NewFD;
7346}
7347
7348/// \brief Perform semantic checking of a new function declaration.
7349///
7350/// Performs semantic analysis of the new function declaration
7351/// NewFD. This routine performs all semantic checking that does not
7352/// require the actual declarator involved in the declaration, and is
7353/// used both for the declaration of functions as they are parsed
7354/// (called via ActOnDeclarator) and for the declaration of functions
7355/// that have been instantiated via C++ template instantiation (called
7356/// via InstantiateDecl).
7357///
James Dennettefce31f2012-06-22 08:10:18 +00007358/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorfd056bc2009-10-13 16:30:37 +00007359/// an explicit specialization of the previous declaration.
7360///
Chris Lattnereaaebc72009-04-25 08:06:05 +00007361/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007362///
James Dennettefce31f2012-06-22 08:10:18 +00007363/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007364bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00007365 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007366 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00007367 assert(!NewFD->getResultType()->isVariablyModifiedType()
7368 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00007369
Richard Smithdd9459f2013-08-13 18:18:50 +00007370 // Determine whether the type of this function should be merged with
7371 // a previous visible declaration. This never happens for functions in C++,
7372 // and always happens in C if the previous declaration was visible.
7373 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7374 !Previous.isShadowed();
7375
Douglas Gregor7dc80e12013-01-09 00:47:56 +00007376 // Filter out any non-conflicting previous declarations.
7377 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7378
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007379 bool Redeclaration = false;
Richard Smith21c8fa82013-01-14 05:37:29 +00007380 NamedDecl *OldDecl = 0;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007381
Douglas Gregor04495c82009-02-24 01:23:02 +00007382 // Merge or overload the declaration with an existing declaration of
7383 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00007384 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00007385 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007386 // a declaration that requires merging. If it's an overload,
7387 // there's no more work to do here; we'll just add the new
7388 // function to the scope.
John McCall871b2e72009-12-09 03:35:25 +00007389 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola90cc3902013-04-15 12:49:13 +00007390 NamedDecl *Candidate = Previous.getFoundDecl();
7391 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7392 Redeclaration = true;
7393 OldDecl = Candidate;
7394 }
John McCall871b2e72009-12-09 03:35:25 +00007395 } else {
John McCallad00b772010-06-16 08:42:20 +00007396 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7397 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00007398 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007399 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00007400 break;
7401
7402 case Ovl_NonFunction:
7403 Redeclaration = true;
7404 break;
7405
7406 case Ovl_Overload:
7407 Redeclaration = false;
7408 break;
John McCall68263142009-11-18 22:49:29 +00007409 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00007410
David Blaikie4e4d0842012-03-11 07:00:24 +00007411 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00007412 // If a function name is overloadable in C, then every function
7413 // with that name must be marked "overloadable".
7414 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7415 << Redeclaration << NewFD;
7416 NamedDecl *OverloadedDecl = 0;
7417 if (Redeclaration)
7418 OverloadedDecl = OldDecl;
7419 else if (!Previous.empty())
7420 OverloadedDecl = Previous.getRepresentativeDecl();
7421 if (OverloadedDecl)
7422 Diag(OverloadedDecl->getLocation(),
7423 diag::note_attribute_overloadable_prev_overload);
7424 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7425 Context));
7426 }
John McCall68263142009-11-18 22:49:29 +00007427 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007428 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007429
Richard Smithaa4bc182013-06-30 09:48:50 +00007430 // Check for a previous extern "C" declaration with this name.
7431 if (!Redeclaration &&
7432 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7433 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7434 if (!Previous.empty()) {
7435 // This is an extern "C" declaration with the same name as a previous
7436 // declaration, and thus redeclares that entity...
7437 Redeclaration = true;
7438 OldDecl = Previous.getFoundDecl();
Richard Smithdd9459f2013-08-13 18:18:50 +00007439 MergeTypeWithPrevious = false;
Richard Smithaa4bc182013-06-30 09:48:50 +00007440
7441 // ... except in the presence of __attribute__((overloadable)).
7442 if (OldDecl->hasAttr<OverloadableAttr>()) {
7443 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7444 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7445 << Redeclaration << NewFD;
7446 Diag(Previous.getFoundDecl()->getLocation(),
7447 diag::note_attribute_overloadable_prev_overload);
7448 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7449 Context));
7450 }
7451 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7452 Redeclaration = false;
7453 OldDecl = 0;
7454 }
7455 }
7456 }
7457 }
7458
Richard Smith21c8fa82013-01-14 05:37:29 +00007459 // C++11 [dcl.constexpr]p8:
7460 // A constexpr specifier for a non-static member function that is not
7461 // a constructor declares that member function to be const.
7462 //
7463 // This needs to be delayed until we know whether this is an out-of-line
7464 // definition of a static member function.
Richard Smith84046262013-04-21 01:08:50 +00007465 //
7466 // This rule is not present in C++1y, so we produce a backwards
7467 // compatibility warning whenever it happens in C++11.
Richard Smith21c8fa82013-01-14 05:37:29 +00007468 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith84046262013-04-21 01:08:50 +00007469 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7470 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith21c8fa82013-01-14 05:37:29 +00007471 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7472 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7473 if (FunctionTemplateDecl *OldTD =
7474 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7475 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7476 if (!OldMD || !OldMD->isStatic()) {
7477 const FunctionProtoType *FPT =
7478 MD->getType()->castAs<FunctionProtoType>();
7479 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7480 EPI.TypeQuals |= Qualifiers::Const;
7481 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00007482 FPT->getArgTypes(), EPI));
Richard Smith84046262013-04-21 01:08:50 +00007483
7484 // Warn that we did this, if we're not performing template instantiation.
7485 // In that case, we'll have warned already when the template was defined.
7486 if (ActiveTemplateInstantiations.empty()) {
7487 SourceLocation AddConstLoc;
7488 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7489 .IgnoreParens().getAs<FunctionTypeLoc>())
7490 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7491
7492 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7493 << FixItHint::CreateInsertion(AddConstLoc, " const");
7494 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007495 }
7496 }
7497
7498 if (Redeclaration) {
7499 // NewFD and OldDecl represent declarations that need to be
7500 // merged.
Richard Smithdd9459f2013-08-13 18:18:50 +00007501 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith21c8fa82013-01-14 05:37:29 +00007502 NewFD->setInvalidDecl();
7503 return Redeclaration;
7504 }
7505
7506 Previous.clear();
7507 Previous.addDecl(OldDecl);
7508
7509 if (FunctionTemplateDecl *OldTemplateDecl
7510 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7511 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7512 FunctionTemplateDecl *NewTemplateDecl
7513 = NewFD->getDescribedFunctionTemplate();
7514 assert(NewTemplateDecl && "Template/non-template mismatch");
7515 if (CXXMethodDecl *Method
7516 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7517 Method->setAccess(OldTemplateDecl->getAccess());
7518 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007519 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007520
7521 // If this is an explicit specialization of a member that is a function
7522 // template, mark it as a member specialization.
7523 if (IsExplicitSpecialization &&
7524 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7525 NewTemplateDecl->setMemberSpecialization();
7526 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00007527 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007528
7529 } else {
John McCalld5617ee2013-01-25 22:31:03 +00007530 // This needs to happen first so that 'inline' propagates.
Richard Smith21c8fa82013-01-14 05:37:29 +00007531 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCalld5617ee2013-01-25 22:31:03 +00007532
7533 if (isa<CXXMethodDecl>(NewFD)) {
7534 // A valid redeclaration of a C++ method must be out-of-line,
7535 // but (unfortunately) it's not necessarily a definition
7536 // because of templates, which means that the previous
7537 // declaration is not necessarily from the class definition.
7538
7539 // For just setting the access, that doesn't matter.
7540 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7541 NewFD->setAccess(oldMethod->getAccess());
7542
7543 // Update the key-function state if necessary for this ABI.
7544 if (NewFD->isInlined() &&
7545 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7546 // setNonKeyFunction needs to work with the original
7547 // declaration from the class definition, and isVirtual() is
7548 // just faster in that case, so map back to that now.
Rafael Espindolabc650912013-10-17 15:37:26 +00007549 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCalld5617ee2013-01-25 22:31:03 +00007550 if (oldMethod->isVirtual()) {
7551 Context.setNonKeyFunction(oldMethod);
7552 }
7553 }
7554 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007555 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00007556 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007557
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007558 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00007559 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007560 // C++-specific checks.
7561 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7562 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00007563 } else if (CXXDestructorDecl *Destructor =
7564 dyn_cast<CXXDestructorDecl>(NewFD)) {
7565 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007566 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00007567
Douglas Gregor4923aa22010-07-02 20:37:36 +00007568 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00007569 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007570 if (!ClassType->isDependentType()) {
7571 DeclarationName Name
7572 = Context.DeclarationNames.getCXXDestructorName(
7573 Context.getCanonicalType(ClassType));
7574 if (NewFD->getDeclName() != Name) {
7575 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007576 NewFD->setInvalidDecl();
7577 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007578 }
7579 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007580 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00007581 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007582 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00007583 }
7584
7585 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00007586 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7587 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00007588 !Method->getDescribedFunctionTemplate() &&
7589 Method->isCanonicalDecl()) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007590 if (AddOverriddenMethods(Method->getParent(), Method)) {
7591 // If the function was marked as "static", we have a problem.
7592 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie5708c182012-10-17 00:47:58 +00007593 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007594 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00007595 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007596 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007597
7598 if (Method->isStatic())
7599 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00007600 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007601
7602 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7603 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007604 CheckOverloadedOperatorDeclaration(NewFD)) {
7605 NewFD->setInvalidDecl();
7606 return Redeclaration;
7607 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007608
7609 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7610 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007611 CheckLiteralOperatorDeclaration(NewFD)) {
7612 NewFD->setInvalidDecl();
7613 return Redeclaration;
7614 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007615
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007616 // In C++, check default arguments now that we have merged decls. Unless
7617 // the lexical context is the class, because in this case this is done
7618 // during delayed parsing anyway.
7619 if (!CurContext->isRecord())
7620 CheckCXXDefaultArguments(NewFD);
Warren Hunt2d023ec2013-11-01 23:46:51 +00007621
Douglas Gregorb68e3992010-12-21 19:47:46 +00007622 // If this function declares a builtin function, check the type of this
7623 // declaration against the expected type for the builtin.
7624 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7625 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanian9ef15182013-01-05 21:54:55 +00007626 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregorb68e3992010-12-21 19:47:46 +00007627 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7628 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7629 // The type of this function differs from the type of the builtin,
7630 // so forget about the builtin entirely.
7631 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7632 }
7633 }
Warren Hunt2d023ec2013-11-01 23:46:51 +00007634
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007635 // If this function is declared as being extern "C", then check to see if
7636 // the function returns a UDT (class, struct, or union type) that is not C
7637 // compatible, and if it does, warn the user.
Fariborz Jahanian96db3292013-03-14 23:09:00 +00007638 // But, issue any diagnostic on the first declaration only.
7639 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007640 QualType R = NewFD->getResultType();
Hans Wennborg168c07b2012-07-24 17:59:41 +00007641 if (R->isIncompleteType() && !R->isVoidType())
7642 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7643 << NewFD << R;
Douglas Gregorb38b4912012-08-07 06:14:34 +00007644 else if (!R.isPODType(Context) && !R->isVoidType() &&
7645 !R->isObjCObjectPointerType())
Hans Wennborg168c07b2012-07-24 17:59:41 +00007646 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007647 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007648 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007649 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007650}
7651
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007652static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7653 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7654 if (!TSI)
7655 return SourceRange();
7656
7657 TypeLoc TL = TSI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00007658 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007659 if (!FunctionTL)
7660 return SourceRange();
7661
David Blaikie39e6ab42013-02-18 22:06:02 +00007662 TypeLoc ResultTL = FunctionTL.getResultLoc();
7663 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007664 return ResultTL.getSourceRange();
7665
7666 return SourceRange();
7667}
7668
David Blaikie14068e82011-09-08 06:33:04 +00007669void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00007670 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7671 // static or constexpr is ill-formed.
Richard Smithde03c152013-01-17 22:16:11 +00007672 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7673 // appear in a declaration of main.
John McCall13591ed2009-07-25 04:36:53 +00007674 // static main is not an error under C99, but we should warn about it.
Richard Smithde03c152013-01-17 22:16:11 +00007675 // We accept _Noreturn main as an extension.
David Blaikie14068e82011-09-08 06:33:04 +00007676 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00007677 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00007678 ? diag::err_static_main : diag::warn_static_main)
7679 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7680 if (FD->isInlineSpecified())
7681 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7682 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko445743d2013-01-21 11:25:03 +00007683 if (DS.isNoreturnSpecified()) {
7684 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7685 SourceRange NoreturnRange(NoreturnLoc,
7686 PP.getLocForEndOfToken(NoreturnLoc));
7687 Diag(NoreturnLoc, diag::ext_noreturn_main);
7688 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7689 << FixItHint::CreateRemoval(NoreturnRange);
7690 }
Richard Smitha5065862012-02-04 06:10:17 +00007691 if (FD->isConstexpr()) {
7692 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7693 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7694 FD->setConstexpr(false);
7695 }
John McCall13591ed2009-07-25 04:36:53 +00007696
Joey Goulyc879fe52013-11-05 12:30:39 +00007697 if (getLangOpts().OpenCL) {
7698 Diag(FD->getLocation(), diag::err_opencl_no_main)
7699 << FD->hasAttr<OpenCLKernelAttr>();
7700 FD->setInvalidDecl();
7701 return;
7702 }
7703
John McCall13591ed2009-07-25 04:36:53 +00007704 QualType T = FD->getType();
7705 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00007706 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007707
John McCall75d8ba32012-02-14 19:50:52 +00007708 // All the standards say that main() should should return 'int'.
7709 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7710 // In C and C++, main magically returns 0 if you fall off the end;
7711 // set the flag which tells us that.
7712 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7713 FD->setHasImplicitReturnZero(true);
7714
7715 // In C with GNU extensions we allow main() to have non-integer return
7716 // type, but we should warn about the extension, and we disable the
7717 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00007718 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00007719 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7720
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007721 SourceRange ResultRange = getResultSourceRange(FD);
7722 if (ResultRange.isValid())
7723 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7724 << FixItHint::CreateReplacement(ResultRange, "int");
7725
John McCall75d8ba32012-02-14 19:50:52 +00007726 // Otherwise, this is just a flat-out error.
7727 } else {
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007728 SourceRange ResultRange = getResultSourceRange(FD);
7729 if (ResultRange.isValid())
7730 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7731 << FixItHint::CreateReplacement(ResultRange, "int");
7732 else
7733 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7734
John McCall13591ed2009-07-25 04:36:53 +00007735 FD->setInvalidDecl(true);
7736 }
7737
7738 // Treat protoless main() as nullary.
7739 if (isa<FunctionNoProtoType>(FT)) return;
7740
7741 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7742 unsigned nparams = FTP->getNumArgs();
7743 assert(FD->getNumParams() == nparams);
7744
John McCall66755862009-12-24 09:58:38 +00007745 bool HasExtraParameters = (nparams > 3);
7746
7747 // Darwin passes an undocumented fourth argument of type char**. If
7748 // other platforms start sprouting these, the logic below will start
7749 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007750 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00007751 HasExtraParameters = false;
7752
7753 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00007754 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7755 FD->setInvalidDecl(true);
7756 nparams = 3;
7757 }
7758
7759 // FIXME: a lot of the following diagnostics would be improved
7760 // if we had some location information about types.
7761
7762 QualType CharPP =
7763 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00007764 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00007765
7766 for (unsigned i = 0; i < nparams; ++i) {
7767 QualType AT = FTP->getArgType(i);
7768
7769 bool mismatch = true;
7770
7771 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7772 mismatch = false;
7773 else if (Expected[i] == CharPP) {
7774 // As an extension, the following forms are okay:
7775 // char const **
7776 // char const * const *
7777 // char * const *
7778
John McCall0953e762009-09-24 19:53:00 +00007779 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00007780 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00007781 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7782 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith485b3122013-01-29 02:49:47 +00007783 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7784 Context.CharTy)) {
John McCall13591ed2009-07-25 04:36:53 +00007785 qs.removeConst();
7786 mismatch = !qs.empty();
7787 }
7788 }
7789
7790 if (mismatch) {
7791 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7792 // TODO: suggest replacing given type with expected type
7793 FD->setInvalidDecl(true);
7794 }
7795 }
7796
7797 if (nparams == 1 && !FD->isInvalidDecl()) {
7798 Diag(FD->getLocation(), diag::warn_main_one_arg);
7799 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007800
7801 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemere9f6f332013-09-16 22:44:20 +00007802 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7803 FD->setInvalidDecl();
7804 }
7805}
7806
7807void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7808 QualType T = FD->getType();
7809 assert(T->isFunctionType() && "function decl is not of function type");
7810 const FunctionType *FT = T->castAs<FunctionType>();
7811
7812 // Set an implicit return of 'zero' if the function can return some integral,
7813 // enumeration, pointer or nullptr type.
7814 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7815 FT->getResultType()->isAnyPointerType() ||
7816 FT->getResultType()->isNullPtrType())
7817 // DllMain is exempt because a return value of zero means it failed.
7818 if (FD->getName() != "DllMain")
7819 FD->setHasImplicitReturnZero(true);
7820
7821 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7822 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007823 FD->setInvalidDecl();
7824 }
John McCall8c4859a2009-07-24 03:03:21 +00007825}
7826
Eli Friedmanc594b322008-05-20 13:48:25 +00007827bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007828 // FIXME: Need strict checking. In C89, we need to check for
7829 // any assignment, increment, decrement, function-calls, or
7830 // commas outside of a sizeof. In C99, it's the same list,
7831 // except that the aforementioned are allowed in unevaluated
7832 // expressions. Everything else falls under the
7833 // "may accept other forms of constant expressions" exception.
7834 // (We never end up here for C++, so the constant expression
7835 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00007836 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00007837 return false;
Eli Friedman21298282009-02-26 04:47:58 +00007838 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7839 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00007840 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00007841}
7842
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007843namespace {
7844 // Visits an initialization expression to see if OrigDecl is evaluated in
7845 // its own initialization and throws a warning if it does.
7846 class SelfReferenceChecker
7847 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7848 Sema &S;
7849 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00007850 bool isRecordType;
7851 bool isPODType;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007852 bool isReferenceType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007853
7854 public:
7855 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7856
7857 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00007858 S(S), OrigDecl(OrigDecl) {
7859 isPODType = false;
7860 isRecordType = false;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007861 isReferenceType = false;
Richard Trieu898267f2011-09-01 21:44:13 +00007862 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7863 isPODType = VD->getType().isPODType(S.Context);
7864 isRecordType = VD->getType()->isRecordType();
Hans Wennborg8be9e772012-08-17 10:12:33 +00007865 isReferenceType = VD->getType()->isReferenceType();
Richard Trieu898267f2011-09-01 21:44:13 +00007866 }
7867 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007868
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007869 // For most expressions, the cast is directly above the DeclRefExpr.
7870 // For conditional operators, the cast can be outside the conditional
7871 // operator if both expressions are DeclRefExpr's.
7872 void HandleValue(Expr *E) {
Richard Trieu568f7852012-10-01 17:39:51 +00007873 if (isReferenceType)
7874 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007875 E = E->IgnoreParenImpCasts();
7876 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7877 HandleDeclRefExpr(DRE);
7878 return;
7879 }
7880
7881 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7882 HandleValue(CO->getTrueExpr());
7883 HandleValue(CO->getFalseExpr());
Richard Trieu6b2cc422012-10-03 00:41:36 +00007884 return;
7885 }
7886
7887 if (isa<MemberExpr>(E)) {
7888 Expr *Base = E->IgnoreParenImpCasts();
7889 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7890 // Check for static member variables and don't warn on them.
7891 if (!isa<FieldDecl>(ME->getMemberDecl()))
7892 return;
7893 Base = ME->getBase()->IgnoreParenImpCasts();
7894 }
7895 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7896 HandleDeclRefExpr(DRE);
7897 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007898 }
7899 }
7900
Richard Trieu568f7852012-10-01 17:39:51 +00007901 // Reference types are handled here since all uses of references are
7902 // bad, not just r-value uses.
7903 void VisitDeclRefExpr(DeclRefExpr *E) {
7904 if (isReferenceType)
7905 HandleDeclRefExpr(E);
7906 }
7907
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007908 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu6b2cc422012-10-03 00:41:36 +00007909 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007910 (isRecordType && E->getCastKind() == CK_NoOp))
7911 HandleValue(E->getSubExpr());
7912
7913 Inherited::VisitImplicitCastExpr(E);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007914 }
7915
Richard Trieu898267f2011-09-01 21:44:13 +00007916 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007917 // Don't warn on arrays since they can be treated as pointers.
Richard Trieu47eb8982011-09-07 00:58:53 +00007918 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007919
Richard Trieu6b2cc422012-10-03 00:41:36 +00007920 // Warn when a non-static method call is followed by non-static member
7921 // field accesses, which is followed by a DeclRefExpr.
7922 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7923 bool Warn = (MD && !MD->isStatic());
7924 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7925 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7926 if (!isa<FieldDecl>(ME->getMemberDecl()))
7927 Warn = false;
7928 Base = ME->getBase()->IgnoreParenImpCasts();
7929 }
Richard Trieu898267f2011-09-01 21:44:13 +00007930
Richard Trieu6b2cc422012-10-03 00:41:36 +00007931 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7932 if (Warn)
7933 HandleDeclRefExpr(DRE);
7934 return;
7935 }
7936
7937 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7938 // Visit that expression.
7939 Visit(Base);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007940 }
7941
Richard Trieu8af742a2013-03-26 03:41:40 +00007942 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7943 if (E->getNumArgs() > 0)
7944 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7945 HandleDeclRefExpr(DRE);
7946
7947 Inherited::VisitCXXOperatorCallExpr(E);
7948 }
7949
Richard Trieu898267f2011-09-01 21:44:13 +00007950 void VisitUnaryOperator(UnaryOperator *E) {
7951 // For POD record types, addresses of its own members are well-defined.
Richard Trieu6b2cc422012-10-03 00:41:36 +00007952 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7953 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7954 if (!isPODType)
7955 HandleValue(E->getSubExpr());
7956 return;
7957 }
Richard Trieu898267f2011-09-01 21:44:13 +00007958 Inherited::VisitUnaryOperator(E);
Richard Smith0f2fc5f2013-05-03 19:16:22 +00007959 }
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007960
7961 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7962
Richard Trieu898267f2011-09-01 21:44:13 +00007963 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumif3052792013-01-19 01:54:35 +00007964 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007965 if (OrigDecl != ReferenceDecl) return;
Ted Kremenek39371b82013-01-19 04:33:14 +00007966 unsigned diag;
7967 if (isReferenceType) {
7968 diag = diag::warn_uninit_self_reference_in_reference_init;
7969 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7970 diag = diag::warn_static_self_reference_in_init;
7971 } else {
7972 diag = diag::warn_uninit_self_reference_in_init;
7973 }
7974
Richard Trieu898267f2011-09-01 21:44:13 +00007975 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborg5965b7c2012-08-20 08:52:22 +00007976 S.PDiag(diag)
Hans Wennborg7821e072012-09-21 08:58:33 +00007977 << DRE->getNameInfo().getName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00007978 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00007979 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007980 }
7981 };
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007982
Richard Trieu568f7852012-10-01 17:39:51 +00007983 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7984 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7985 bool DirectInit) {
7986 // Parameters arguments are occassionially constructed with itself,
7987 // for instance, in recursive functions. Skip them.
7988 if (isa<ParmVarDecl>(OrigDecl))
7989 return;
7990
7991 E = E->IgnoreParens();
7992
7993 // Skip checking T a = a where T is not a record or reference type.
7994 // Doing so is a way to silence uninitialized warnings.
7995 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7996 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7997 if (ICE->getCastKind() == CK_LValueToRValue)
7998 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7999 if (DRE->getDecl() == OrigDecl)
8000 return;
8001
8002 SelfReferenceChecker(S, OrigDecl).Visit(E);
8003 }
Richard Trieu898267f2011-09-01 21:44:13 +00008004}
8005
Douglas Gregor09f41cf2009-01-14 15:45:31 +00008006/// AddInitializerToDecl - Adds the initializer Init to the
8007/// declaration dcl. If DirectInit is true, this is C++ direct
8008/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00008009void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8010 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008011 // If there is no declaration, there was an error parsing it. Just ignore
8012 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00008013 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008014 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008015
Douglas Gregor021c3b32009-03-11 23:00:04 +00008016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8017 // With declarators parsed the way they are, the parser cannot
8018 // distinguish between a normal initializer and a pure-specifier.
8019 // Thus this grotesque test.
8020 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00008021 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00008022 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8023 CheckPureMethod(Method, Init->getSourceRange());
8024 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00008025 Diag(Method->getLocation(), diag::err_member_function_initialization)
8026 << Method->getDeclName() << Init->getSourceRange();
8027 Method->setInvalidDecl();
8028 }
8029 return;
8030 }
8031
Steve Naroff410e3e22007-09-12 20:13:48 +00008032 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8033 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00008034 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8035 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00008036 RealDecl->setInvalidDecl();
8037 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00008038 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008039 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8040
Richard Smith01888722011-12-15 19:20:59 +00008041 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00008042 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008043 Expr *DeduceInit = Init;
8044 // Initializer could be a C++ direct-initializer. Deduction only works if it
8045 // contains exactly one expression.
8046 if (CXXDirectInit) {
8047 if (CXXDirectInit->getNumExprs() == 0) {
8048 // It isn't possible to write this directly, but it is possible to
8049 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00008050 Diag(CXXDirectInit->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008051 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8052 : diag::err_auto_var_init_no_expression)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008053 << VDecl->getDeclName() << VDecl->getType()
8054 << VDecl->getSourceRange();
8055 RealDecl->setInvalidDecl();
8056 return;
8057 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00008058 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008059 VDecl->isInitCapture()
8060 ? diag::err_init_capture_multiple_expressions
8061 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008062 << VDecl->getDeclName() << VDecl->getType()
8063 << VDecl->getSourceRange();
8064 RealDecl->setInvalidDecl();
8065 return;
8066 } else {
8067 DeduceInit = CXXDirectInit->getExpr(0);
8068 }
8069 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008070
8071 // Expressions default to 'id' when we're in a debugger.
8072 bool DefaultedToAuto = false;
8073 if (getLangOpts().DebuggerCastResultToId &&
8074 Init->getType() == Context.UnknownAnyTy) {
8075 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8076 if (Result.isInvalid()) {
8077 VDecl->setInvalidDecl();
8078 return;
8079 }
8080 Init = Result.take();
8081 DefaultedToAuto = true;
8082 }
Richard Smith9b131752013-04-30 21:23:01 +00008083
8084 QualType DeducedType;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008085 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00008086 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008087 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9b131752013-04-30 21:23:01 +00008088 if (DeducedType.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008089 RealDecl->setInvalidDecl();
8090 return;
8091 }
Richard Smith9b131752013-04-30 21:23:01 +00008092 VDecl->setType(DeducedType);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00008093 assert(VDecl->isLinkageValid());
Rafael Espindola2d9e8832013-03-12 21:06:00 +00008094
John McCallf85e1932011-06-15 23:02:42 +00008095 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00008096 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00008097 VDecl->setInvalidDecl();
8098
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008099 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8100 // 'id' instead of a specific object type prevents most of our usual checks.
8101 // We only want to warn outside of template instantiations, though:
8102 // inside a template, the 'id' could have come from a parameter.
Douglas Gregor1344e942013-03-07 22:57:58 +00008103 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith9b131752013-04-30 21:23:01 +00008104 DeducedType->isObjCIdType()) {
8105 SourceLocation Loc =
8106 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008107 Diag(Loc, diag::warn_auto_var_is_id)
8108 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8109 }
8110
Richard Smith34b41d92011-02-20 03:19:35 +00008111 // If this is a redeclaration, check that the type we just deduced matches
8112 // the previously declared type.
Richard Smithdd9459f2013-08-13 18:18:50 +00008113 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8114 // We never need to merge the type, because we cannot form an incomplete
8115 // array of auto, nor deduce such a type.
8116 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8117 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00008118
8119 // Check the deduced type is valid for a variable declaration.
8120 CheckVariableDeclarationType(VDecl);
8121 if (VDecl->isInvalidDecl())
8122 return;
Richard Smith34b41d92011-02-20 03:19:35 +00008123 }
Richard Smith01888722011-12-15 19:20:59 +00008124
8125 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8126 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8127 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8128 VDecl->setInvalidDecl();
8129 return;
8130 }
8131
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008132 if (!VDecl->getType()->isDependentType()) {
8133 // A definition must end up with a complete type, which means it must be
8134 // complete with the restriction that an array type might be completed by
8135 // the initializer; note that later code assumes this restriction.
8136 QualType BaseDeclType = VDecl->getType();
8137 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8138 BaseDeclType = Array->getElementType();
8139 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8140 diag::err_typecheck_decl_incomplete_type)) {
8141 RealDecl->setInvalidDecl();
8142 return;
8143 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008144
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008145 // The variable can not have an abstract class type.
8146 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8147 diag::err_abstract_type_in_decl,
8148 AbstractVariableType))
8149 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00008150 }
8151
Sebastian Redl31310a22010-02-01 20:16:42 +00008152 const VarDecl *Def;
8153 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00008154 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00008155 << VDecl->getDeclName();
8156 Diag(Def->getLocation(), diag::note_previous_definition);
8157 VDecl->setInvalidDecl();
8158 return;
8159 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008160
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008161 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00008162 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00008163 // C++ [class.static.data]p4
8164 // If a static data member is of const integral or const
8165 // enumeration type, its declaration in the class definition can
8166 // specify a constant-initializer which shall be an integral
8167 // constant expression (5.19). In that case, the member can appear
8168 // in integral constant expressions. The member shall still be
8169 // defined in a namespace scope if it is used in the program and the
8170 // namespace scope definition shall not contain an initializer.
8171 //
8172 // We already performed a redefinition check above, but for static
8173 // data members we also need to check whether there was an in-class
8174 // declaration with an initializer.
8175 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00008176 Diag(VDecl->getLocation(), diag::err_redefinition)
8177 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00008178 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8179 return;
8180 }
Douglas Gregor275a3692009-03-10 23:43:53 +00008181
Douglas Gregora31040f2010-12-16 01:31:22 +00008182 if (VDecl->hasLocalStorage())
8183 getCurFunction()->setHasBranchProtectedScope();
8184
8185 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8186 VDecl->setInvalidDecl();
8187 return;
8188 }
8189 }
John McCalle46f62c2010-08-01 01:24:59 +00008190
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008191 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8192 // a kernel function cannot be initialized."
8193 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8194 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8195 VDecl->setInvalidDecl();
8196 return;
8197 }
8198
Steve Naroffbb204692007-09-12 14:07:44 +00008199 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00008200 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00008201 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008202
Douglas Gregor1344e942013-03-07 22:57:58 +00008203 // Expressions default to 'id' when we're in a debugger
8204 // and we are assigning it to a variable of Objective-C pointer type.
8205 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8206 Init->getType() == Context.UnknownAnyTy) {
8207 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8208 if (Result.isInvalid()) {
8209 VDecl->setInvalidDecl();
8210 return;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008211 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008212 Init = Result.take();
8213 }
Richard Smith01888722011-12-15 19:20:59 +00008214
8215 // Perform the initialization.
8216 if (!VDecl->isInvalidDecl()) {
8217 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8218 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00008219 = DirectInit ?
8220 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8221 Init->getLocStart(),
8222 Init->getLocEnd())
8223 : InitializationKind::CreateDirectList(
8224 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00008225 : InitializationKind::CreateCopy(VDecl->getLocation(),
8226 Init->getLocStart());
8227
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008228 MultiExprArg Args = Init;
8229 if (CXXDirectInit)
8230 Args = MultiExprArg(CXXDirectInit->getExprs(),
8231 CXXDirectInit->getNumExprs());
8232
8233 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8234 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith01888722011-12-15 19:20:59 +00008235 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00008236 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00008237 return;
Steve Naroffbb204692007-09-12 14:07:44 +00008238 }
Richard Smith01888722011-12-15 19:20:59 +00008239
8240 Init = Result.takeAs<Expr>();
8241 }
8242
Richard Trieu568f7852012-10-01 17:39:51 +00008243 // Check for self-references within variable initializers.
8244 // Variables declared within a function/method body (except for references)
8245 // are handled by a dataflow analysis.
8246 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8247 VDecl->getType()->isReferenceType()) {
8248 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8249 }
8250
Richard Smith01888722011-12-15 19:20:59 +00008251 // If the type changed, it means we had an incomplete type that was
8252 // completed by the initializer. For example:
8253 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00008254 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00008255 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00008256 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00008257
Jordan Rosee10f4d32012-09-15 02:48:31 +00008258 if (!VDecl->isInvalidDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00008259 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8260
Jordan Rosee10f4d32012-09-15 02:48:31 +00008261 if (VDecl->hasAttr<BlocksAttr>())
8262 checkRetainCycles(VDecl, Init);
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008263
8264 // It is safe to assign a weak reference into a strong variable.
8265 // Although this code can still have problems:
8266 // id x = self.weakProp;
8267 // id y = self.weakProp;
8268 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8269 // paths through the function. This should be revisited if
8270 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek904a3262012-12-20 22:31:27 +00008271 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008272 DiagnosticsEngine::Level Level =
8273 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8274 Init->getLocStart());
8275 if (Level != DiagnosticsEngine::Ignored)
8276 getCurFunction()->markSafeWeakUse(Init);
8277 }
Jordan Rosee10f4d32012-09-15 02:48:31 +00008278 }
8279
Richard Smith41956372013-01-14 22:39:08 +00008280 // The initialization is usually a full-expression.
8281 //
8282 // FIXME: If this is a braced initialization of an aggregate, it is not
8283 // an expression, and each individual field initializer is a separate
8284 // full-expression. For instance, in:
8285 //
8286 // struct Temp { ~Temp(); };
8287 // struct S { S(Temp); };
8288 // struct T { S a, b; } t = { Temp(), Temp() }
8289 //
8290 // we should destroy the first Temp before constructing the second.
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008291 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8292 false,
8293 VDecl->isConstexpr());
Richard Smith41956372013-01-14 22:39:08 +00008294 if (Result.isInvalid()) {
8295 VDecl->setInvalidDecl();
8296 return;
8297 }
8298 Init = Result.take();
8299
Richard Smith01888722011-12-15 19:20:59 +00008300 // Attach the initializer to the decl.
8301 VDecl->setInit(Init);
8302
8303 if (VDecl->isLocalVarDecl()) {
8304 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8305 // static storage duration shall be constant expressions or string literals.
8306 // C++ does not have this restriction.
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008307 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8308 if (VDecl->getStorageClass() == SC_Static)
8309 CheckForConstantInitializer(Init, DclT);
8310 // C89 is stricter than C99 for non-static aggregate types.
8311 // C89 6.5.7p3: All the expressions [...] in an initializer list
8312 // for an object that has aggregate or union type shall be
8313 // constant expressions.
8314 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanella82026302013-07-22 19:10:20 +00008315 isa<InitListExpr>(Init) &&
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008316 !Init->isConstantInitializer(Context, false))
8317 Diag(Init->getExprLoc(),
8318 diag::ext_aggregate_init_not_constant)
8319 << Init->getSourceRange();
8320 }
Mike Stump1eb44332009-09-09 15:08:12 +00008321 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00008322 VDecl->getLexicalDeclContext()->isRecord()) {
8323 // This is an in-class initialization for a static data member, e.g.,
8324 //
8325 // struct S {
8326 // static const int value = 17;
8327 // };
8328
Douglas Gregor021c3b32009-03-11 23:00:04 +00008329 // C++ [class.mem]p4:
8330 // A member-declarator can contain a constant-initializer only
8331 // if it declares a static member (9.4) of const integral or
8332 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00008333 //
Richard Smith01888722011-12-15 19:20:59 +00008334 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00008335 // If a non-volatile const static data member is of integral or
8336 // enumeration type, its declaration in the class definition can
8337 // specify a brace-or-equal-initializer in which every initalizer-clause
8338 // that is an assignment-expression is a constant expression. A static
8339 // data member of literal type can be declared in the class definition
8340 // with the constexpr specifier; if so, its declaration shall specify a
8341 // brace-or-equal-initializer in which every initializer-clause that is
8342 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00008343
8344 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00008345 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00008346
Richard Smithc6d990a2011-09-29 19:11:37 +00008347 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00008348 // type. We separately check that every constexpr variable is of literal
8349 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00008350 } else if (VDecl->isConstexpr()) {
8351
John McCall4e635642010-09-10 23:21:22 +00008352 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00008353 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00008354 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8355 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008356 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008357
8358 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00008359 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00008360 // Check whether the expression is a constant expression.
8361 SourceLocation Loc;
Richard Smith80ad52f2013-01-02 11:42:31 +00008362 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00008363 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00008364 // in-class initializer cannot be volatile.
8365 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8366 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00008367 ; // Nothing to check.
8368 else if (Init->isIntegerConstantExpr(Context, &Loc))
8369 ; // Ok, it's an ICE!
8370 else if (Init->isEvaluatable(Context)) {
8371 // If we can constant fold the initializer through heroics, accept it,
8372 // but report this as a use of an extension for -pedantic.
8373 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8374 << Init->getSourceRange();
8375 } else {
8376 // Otherwise, this is some crazy unknown case. Report the issue at the
8377 // location provided by the isIntegerConstantExpr failed check.
8378 Diag(Loc, diag::err_in_class_initializer_non_constant)
8379 << Init->getSourceRange();
8380 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008381 }
8382
Richard Smith01888722011-12-15 19:20:59 +00008383 // We allow foldable floating-point constants as an extension.
8384 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithb4b1d692013-01-25 04:22:16 +00008385 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8386 // it anyway and provide a fixit to add the 'constexpr'.
8387 if (getLangOpts().CPlusPlus11) {
David Blaikiea367e9d2013-01-29 22:26:08 +00008388 Diag(VDecl->getLocation(),
8389 diag::ext_in_class_initializer_float_type_cxx11)
8390 << DclT << Init->getSourceRange();
8391 Diag(VDecl->getLocStart(),
8392 diag::note_in_class_initializer_float_type_cxx11)
8393 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithb4b1d692013-01-25 04:22:16 +00008394 } else {
8395 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8396 << DclT << Init->getSourceRange();
John McCall4e635642010-09-10 23:21:22 +00008397
Richard Smithb4b1d692013-01-25 04:22:16 +00008398 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8399 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8400 << Init->getSourceRange();
8401 VDecl->setInvalidDecl();
8402 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00008403 }
Richard Smith947be192011-09-29 23:18:34 +00008404
Richard Smith01888722011-12-15 19:20:59 +00008405 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smitha10b9782013-04-22 15:31:51 +00008406 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith947be192011-09-29 23:18:34 +00008407 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00008408 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00008409 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8410 VDecl->setConstexpr(true);
8411
Richard Smithc6d990a2011-09-29 19:11:37 +00008412 } else {
8413 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00008414 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00008415 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008416 }
Steve Naroff248a7532008-04-15 22:42:06 +00008417 } else if (VDecl->isFileVarDecl()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008418 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008419 (!getLangOpts().CPlusPlus ||
Rafael Espindola5b34b9c2013-03-29 07:56:05 +00008420 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smithd0629eb2013-09-27 20:14:12 +00008421 VDecl->isExternC())) &&
8422 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff410e3e22007-09-12 20:13:48 +00008423 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00008424
Richard Smith01888722011-12-15 19:20:59 +00008425 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00008426 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00008427 CheckForConstantInitializer(Init, DclT);
Richard Smith6a570f62013-04-14 20:11:31 +00008428 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8429 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8430 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smithb6b127f2013-04-15 08:07:34 +00008431 !Init->isConstantInitializer(
8432 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6a570f62013-04-14 20:11:31 +00008433 // GNU C++98 edits for __thread, [basic.start.init]p4:
8434 // An object of thread storage duration shall not require dynamic
8435 // initialization.
8436 // FIXME: Need strict checking here.
8437 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8438 if (getLangOpts().CPlusPlus11)
8439 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8440 }
Steve Naroffbb204692007-09-12 14:07:44 +00008441 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008442
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008443 // We will represent direct-initialization similarly to copy-initialization:
8444 // int x(1); -as-> int x = 1;
8445 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8446 //
8447 // Clients that want to distinguish between the two forms, can check for
8448 // direct initializer using VarDecl::getInitStyle().
8449 // A major benefit is that clients that don't particularly care about which
8450 // exactly form was it (like the CodeGen) can handle both cases without
8451 // special case code.
8452
8453 // C++ 8.5p11:
8454 // The form of initialization (using parentheses or '=') is generally
8455 // insignificant, but does matter when the entity being initialized has a
8456 // class type.
8457 if (CXXDirectInit) {
8458 assert(DirectInit && "Call-style initializer must be direct init.");
8459 VDecl->setInitStyle(VarDecl::CallInit);
8460 } else if (DirectInit) {
8461 // This must be list-initialization. No other way is direct-initialization.
8462 VDecl->setInitStyle(VarDecl::ListInit);
8463 }
8464
John McCall2998d6b2011-01-19 11:48:09 +00008465 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00008466}
8467
John McCall7727acf2010-03-31 02:13:20 +00008468/// ActOnInitializerError - Given that there was an error parsing an
8469/// initializer for the given declaration, try to return to some form
8470/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00008471void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00008472 // Our main concern here is re-establishing invariants like "a
8473 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00008474 if (!D || D->isInvalidDecl()) return;
8475
8476 VarDecl *VD = dyn_cast<VarDecl>(D);
8477 if (!VD) return;
8478
Richard Smith34b41d92011-02-20 03:19:35 +00008479 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00008480 if (ParsingInitForAutoVars.count(D)) {
8481 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008482 return;
8483 }
8484
John McCall7727acf2010-03-31 02:13:20 +00008485 QualType Ty = VD->getType();
8486 if (Ty->isDependentType()) return;
8487
8488 // Require a complete type.
8489 if (RequireCompleteType(VD->getLocation(),
8490 Context.getBaseElementType(Ty),
8491 diag::err_typecheck_decl_incomplete_type)) {
8492 VD->setInvalidDecl();
8493 return;
8494 }
8495
8496 // Require an abstract type.
8497 if (RequireNonAbstractType(VD->getLocation(), Ty,
8498 diag::err_abstract_type_in_decl,
8499 AbstractVariableType)) {
8500 VD->setInvalidDecl();
8501 return;
8502 }
8503
8504 // Don't bother complaining about constructors or destructors,
8505 // though.
8506}
8507
John McCalld226f652010-08-21 09:40:31 +00008508void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00008509 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00008510 // If there is no declaration, there was an error parsing it. Just ignore it.
8511 if (RealDecl == 0)
8512 return;
8513
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008514 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8515 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008516
Richard Smithdd4b3502011-12-25 21:17:58 +00008517 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00008518 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00008519 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8520 << Var->getDeclName() << Type;
8521 Var->setInvalidDecl();
8522 return;
8523 }
Mike Stump1eb44332009-09-09 15:08:12 +00008524
Richard Smithdd4b3502011-12-25 21:17:58 +00008525 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00008526 // the constexpr specifier; if so, its declaration shall specify
8527 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00008528 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8529 // the definition of a variable [...] or the declaration of a static data
8530 // member.
8531 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8532 if (Var->isStaticDataMember())
8533 Diag(Var->getLocation(),
8534 diag::err_constexpr_static_mem_var_requires_init)
8535 << Var->getDeclName();
8536 else
8537 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00008538 Var->setInvalidDecl();
8539 return;
8540 }
8541
Douglas Gregor60c93c92010-02-09 07:26:29 +00008542 switch (Var->isThisDeclarationADefinition()) {
8543 case VarDecl::Definition:
8544 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8545 break;
8546
8547 // We have an out-of-line definition of a static data member
8548 // that has an in-class initializer, so we type-check this like
8549 // a declaration.
8550 //
8551 // Fall through
8552
8553 case VarDecl::DeclarationOnly:
8554 // It's only a declaration.
8555
8556 // Block scope. C99 6.7p7: If an identifier for an object is
8557 // declared with no linkage (C99 6.2.2p6), the type for the
8558 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00008559 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008560 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00008561 RequireCompleteType(Var->getLocation(), Type,
8562 diag::err_typecheck_decl_incomplete_type))
8563 Var->setInvalidDecl();
8564
8565 // Make sure that the type is not abstract.
8566 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8567 RequireNonAbstractType(Var->getLocation(), Type,
8568 diag::err_abstract_type_in_decl,
8569 AbstractVariableType))
8570 Var->setInvalidDecl();
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008571 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008572 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008573 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008574 Diag(Var->getLocation(), diag::note_private_extern);
8575 }
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008576
Douglas Gregor60c93c92010-02-09 07:26:29 +00008577 return;
8578
8579 case VarDecl::TentativeDefinition:
8580 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8581 // object that has file scope without an initializer, and without a
8582 // storage-class specifier or with the storage-class specifier "static",
8583 // constitutes a tentative definition. Note: A tentative definition with
8584 // external linkage is valid (C99 6.2.2p5).
8585 if (!Var->isInvalidDecl()) {
8586 if (const IncompleteArrayType *ArrayT
8587 = Context.getAsIncompleteArrayType(Type)) {
8588 if (RequireCompleteType(Var->getLocation(),
8589 ArrayT->getElementType(),
8590 diag::err_illegal_decl_array_incomplete_type))
8591 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00008592 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00008593 // C99 6.9.2p3: If the declaration of an identifier for an object is
8594 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8595 // declared type shall not be an incomplete type.
8596 // NOTE: code such as the following
8597 // static struct s;
8598 // struct s { int a; };
8599 // is accepted by gcc. Hence here we issue a warning instead of
8600 // an error and we do not invalidate the static declaration.
8601 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00008602 if (Var->isFirstDecl())
Douglas Gregor60c93c92010-02-09 07:26:29 +00008603 RequireCompleteType(Var->getLocation(), Type,
8604 diag::ext_typecheck_decl_incomplete_type);
8605 }
8606 }
8607
8608 // Record the tentative definition; we're done.
8609 if (!Var->isInvalidDecl())
8610 TentativeDefinitions.push_back(Var);
8611 return;
8612 }
8613
8614 // Provide a specific diagnostic for uninitialized variable
8615 // definitions with incomplete array type.
8616 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00008617 Diag(Var->getLocation(),
8618 diag::err_typecheck_incomplete_array_needs_initializer);
8619 Var->setInvalidDecl();
8620 return;
8621 }
8622
John McCallb567a8b2010-08-01 01:25:24 +00008623 // Provide a specific diagnostic for uninitialized variable
8624 // definitions with reference type.
8625 if (Type->isReferenceType()) {
8626 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8627 << Var->getDeclName()
8628 << SourceRange(Var->getLocation(), Var->getLocation());
8629 Var->setInvalidDecl();
8630 return;
8631 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008632
8633 // Do not attempt to type-check the default initializer for a
8634 // variable with dependent type.
8635 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00008636 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00008637
Douglas Gregor60c93c92010-02-09 07:26:29 +00008638 if (Var->isInvalidDecl())
8639 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00008640
Douglas Gregor60c93c92010-02-09 07:26:29 +00008641 if (RequireCompleteType(Var->getLocation(),
8642 Context.getBaseElementType(Type),
8643 diag::err_typecheck_decl_incomplete_type)) {
8644 Var->setInvalidDecl();
8645 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008646 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008647
Douglas Gregor60c93c92010-02-09 07:26:29 +00008648 // The variable can not have an abstract class type.
8649 if (RequireNonAbstractType(Var->getLocation(), Type,
8650 diag::err_abstract_type_in_decl,
8651 AbstractVariableType)) {
8652 Var->setInvalidDecl();
8653 return;
8654 }
8655
Douglas Gregor4337dc72011-05-21 17:52:48 +00008656 // Check for jumps past the implicit initializer. C++0x
8657 // clarifies that this applies to a "variable with automatic
8658 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00008659 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00008660 // A program that jumps from a point where a variable with automatic
8661 // storage duration is not in scope to a point where it is in scope is
8662 // ill-formed unless the variable has scalar type, class type with a
8663 // trivial default constructor and a trivial destructor, a cv-qualified
8664 // version of one of these types, or an array of one of the preceding
8665 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00008666 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008667 if (const RecordType *Record
8668 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00008669 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00008670 // Mark the function for further checking even if the looser rules of
8671 // C++11 do not require such checks, so that we can diagnose
8672 // incompatibilities with C++98.
8673 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00008674 getCurFunction()->setHasBranchProtectedScope();
8675 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008676 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00008677
8678 // C++03 [dcl.init]p9:
8679 // If no initializer is specified for an object, and the
8680 // object is of (possibly cv-qualified) non-POD class type (or
8681 // array thereof), the object shall be default-initialized; if
8682 // the object is of const-qualified type, the underlying class
8683 // type shall have a user-declared default
8684 // constructor. Otherwise, if no initializer is specified for
8685 // a non- static object, the object and its subobjects, if
8686 // any, have an indeterminate initial value); if the object
8687 // or any of its subobjects are of const-qualified type, the
8688 // program is ill-formed.
8689 // C++0x [dcl.init]p11:
8690 // If no initializer is specified for an object, the object is
8691 // default-initialized; [...].
8692 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8693 InitializationKind Kind
8694 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00008695
8696 InitializationSequence InitSeq(*this, Entity, Kind, None);
8697 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor4337dc72011-05-21 17:52:48 +00008698 if (Init.isInvalid())
8699 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008700 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008701 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008702 // This is important for template substitution.
8703 Var->setInitStyle(VarDecl::CallInit);
8704 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00008705
John McCall2998d6b2011-01-19 11:48:09 +00008706 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008707 }
8708}
8709
Richard Smithad762fc2011-04-14 22:09:26 +00008710void Sema::ActOnCXXForRangeDecl(Decl *D) {
8711 VarDecl *VD = dyn_cast<VarDecl>(D);
8712 if (!VD) {
8713 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8714 D->setInvalidDecl();
8715 return;
8716 }
8717
8718 VD->setCXXForRangeDecl(true);
8719
8720 // for-range-declaration cannot be given a storage class specifier.
8721 int Error = -1;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008722 switch (VD->getStorageClass()) {
Richard Smithad762fc2011-04-14 22:09:26 +00008723 case SC_None:
8724 break;
8725 case SC_Extern:
8726 Error = 0;
8727 break;
8728 case SC_Static:
8729 Error = 1;
8730 break;
8731 case SC_PrivateExtern:
8732 Error = 2;
8733 break;
8734 case SC_Auto:
8735 Error = 3;
8736 break;
8737 case SC_Register:
8738 Error = 4;
8739 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008740 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00008741 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00008742 }
Richard Smithc6d990a2011-09-29 19:11:37 +00008743 if (VD->isConstexpr())
8744 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00008745 if (Error != -1) {
8746 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8747 << VD->getDeclName() << Error;
8748 D->setInvalidDecl();
8749 }
8750}
8751
John McCall2998d6b2011-01-19 11:48:09 +00008752void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8753 if (var->isInvalidDecl()) return;
8754
John McCallf85e1932011-06-15 23:02:42 +00008755 // In ARC, don't allow jumps past the implicit initialization of a
8756 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00008757 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00008758 var->hasLocalStorage()) {
8759 switch (var->getType().getObjCLifetime()) {
8760 case Qualifiers::OCL_None:
8761 case Qualifiers::OCL_ExplicitNone:
8762 case Qualifiers::OCL_Autoreleasing:
8763 break;
8764
8765 case Qualifiers::OCL_Weak:
8766 case Qualifiers::OCL_Strong:
8767 getCurFunction()->setHasBranchProtectedScope();
8768 break;
8769 }
8770 }
8771
Eli Friedmane4851f22012-10-23 20:19:32 +00008772 if (var->isThisDeclarationADefinition() &&
Eli Friedman2ae28e52013-09-24 23:10:08 +00008773 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimekacaf1102012-12-12 13:26:54 +00008774 getDiagnostics().getDiagnosticLevel(
8775 diag::warn_missing_variable_declarations,
8776 var->getLocation())) {
Eli Friedmane4851f22012-10-23 20:19:32 +00008777 // Find a previous declaration that's not a definition.
8778 VarDecl *prev = var->getPreviousDecl();
8779 while (prev && prev->isThisDeclarationADefinition())
8780 prev = prev->getPreviousDecl();
8781
8782 if (!prev)
8783 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8784 }
8785
Richard Smith6a570f62013-04-14 20:11:31 +00008786 if (var->getTLSKind() == VarDecl::TLS_Static &&
8787 var->getType().isDestructedType()) {
8788 // GNU C++98 edits for __thread, [basic.start.term]p3:
8789 // The type of an object with thread storage duration shall not
8790 // have a non-trivial destructor.
8791 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8792 if (getLangOpts().CPlusPlus11)
8793 Diag(var->getLocation(), diag::note_use_thread_local);
8794 }
8795
John McCall2998d6b2011-01-19 11:48:09 +00008796 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00008797 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00008798
Richard Smitha67d5032012-11-09 23:03:14 +00008799 QualType type = var->getType();
8800 if (type->isDependentType()) return;
John McCall2998d6b2011-01-19 11:48:09 +00008801
8802 // __block variables might require us to capture a copy-initializer.
8803 if (var->hasAttr<BlocksAttr>()) {
8804 // It's currently invalid to ever have a __block variable with an
8805 // array type; should we diagnose that here?
8806
8807 // Regardless, we don't want to ignore array nesting when
8808 // constructing this copy.
John McCall2998d6b2011-01-19 11:48:09 +00008809 if (type->isStructureOrClassType()) {
John McCallb760f112013-03-22 02:10:40 +00008810 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall2998d6b2011-01-19 11:48:09 +00008811 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00008812 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregor6cda3e62013-03-07 22:38:24 +00008813 ExprResult result
8814 = PerformMoveOrCopyInitialization(
8815 InitializedEntity::InitializeBlock(poi, type, false),
8816 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall2998d6b2011-01-19 11:48:09 +00008817 if (!result.isInvalid()) {
8818 result = MaybeCreateExprWithCleanups(result);
8819 Expr *init = result.takeAs<Expr>();
8820 Context.setBlockVarCopyInits(var, init);
8821 }
8822 }
8823 }
8824
Richard Smith66f85712011-11-07 22:16:17 +00008825 Expr *Init = var->getInit();
8826 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smitha67d5032012-11-09 23:03:14 +00008827 QualType baseType = Context.getBaseElementType(type);
Richard Smith66f85712011-11-07 22:16:17 +00008828
Richard Smith9568f0c2012-10-29 18:26:47 +00008829 if (!var->getDeclContext()->isDependentContext() &&
8830 Init && !Init->isValueDependent()) {
Richard Smith099e7f62011-12-19 06:19:21 +00008831 if (IsGlobal && !var->isConstexpr() &&
8832 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8833 var->getLocation())
Eli Friedman21cde052013-07-16 22:40:53 +00008834 != DiagnosticsEngine::Ignored) {
8835 // Warn about globals which don't have a constant initializer. Don't
8836 // warn about globals with a non-trivial destructor because we already
8837 // warned about them.
8838 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8839 if (!(RD && !RD->hasTrivialDestructor()) &&
8840 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8841 Diag(var->getLocation(), diag::warn_global_constructor)
8842 << Init->getSourceRange();
8843 }
Richard Smith099e7f62011-12-19 06:19:21 +00008844
Richard Smith099e7f62011-12-19 06:19:21 +00008845 if (var->isConstexpr()) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008846 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00008847 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8848 SourceLocation DiagLoc = var->getLocation();
8849 // If the note doesn't add any useful information other than a source
8850 // location, fold it into the primary diagnostic.
8851 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8852 diag::note_invalid_subexpr_in_const_expr) {
8853 DiagLoc = Notes[0].first;
8854 Notes.clear();
8855 }
8856 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8857 << var << Init->getSourceRange();
8858 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8859 Diag(Notes[I].first, Notes[I].second);
8860 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00008861 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00008862 // Check whether the initializer of a const variable of integral or
8863 // enumeration type is an ICE now, since we can't tell whether it was
8864 // initialized by a constant expression if we check later.
8865 var->checkInitIsICE();
8866 }
Richard Smith66f85712011-11-07 22:16:17 +00008867 }
John McCall2998d6b2011-01-19 11:48:09 +00008868
8869 // Require the destructor.
8870 if (const RecordType *recordType = baseType->getAs<RecordType>())
8871 FinalizeVarWithDestructor(var, recordType);
8872}
8873
Richard Smith483b9f32011-02-21 20:05:19 +00008874/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8875/// any semantic actions necessary after any initializer has been attached.
8876void
8877Sema::FinalizeDeclaration(Decl *ThisDecl) {
8878 // Note that we are no longer parsing the initializer for this declaration.
8879 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008880
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008881 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindolada844b32013-01-03 04:05:19 +00008882 if (!VD)
8883 return;
8884
Rafael Espindola29535ba2013-08-16 23:18:50 +00008885 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8886 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8887 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8888 VD->dropAttr<UsedAttr>();
8889 }
8890 }
8891
Rafael Espindolab1c0e202013-10-22 21:39:03 +00008892 if (!VD->isInvalidDecl() &&
8893 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8894 if (const VarDecl *Def = VD->getDefinition()) {
8895 if (Def->hasAttr<AliasAttr>()) {
8896 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8897 << VD->getDeclName();
8898 Diag(Def->getLocation(), diag::note_previous_definition);
8899 VD->setInvalidDecl();
8900 }
8901 }
8902 }
8903
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008904 const DeclContext *DC = VD->getDeclContext();
8905 // If there's a #pragma GCC visibility in scope, and this isn't a class
8906 // member, set the visibility of this variable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008907 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008908 AddPushedVisibilityAttribute(VD);
8909
Rafael Espindola6769ccb2013-01-03 04:29:20 +00008910 if (VD->isFileVarDecl())
8911 MarkUnusedFileScopedDecl(VD);
8912
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008913 // Now we have parsed the initializer and can update the table of magic
8914 // tag values.
Rafael Espindolada844b32013-01-03 04:05:19 +00008915 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8916 !VD->getType()->isIntegralOrEnumerationType())
8917 return;
8918
8919 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8920 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8921 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8922 I != E; ++I) {
8923 const Expr *MagicValueExpr = VD->getInit();
8924 if (!MagicValueExpr) {
8925 continue;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008926 }
Rafael Espindolada844b32013-01-03 04:05:19 +00008927 llvm::APSInt MagicValueInt;
8928 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8929 Diag(I->getRange().getBegin(),
8930 diag::err_type_tag_for_datatype_not_ice)
8931 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8932 continue;
8933 }
8934 if (MagicValueInt.getActiveBits() > 64) {
8935 Diag(I->getRange().getBegin(),
8936 diag::err_type_tag_for_datatype_too_large)
8937 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8938 continue;
8939 }
8940 uint64_t MagicValue = MagicValueInt.getZExtValue();
8941 RegisterTypeTagForDatatype(I->getArgumentKind(),
8942 MagicValue,
8943 I->getMatchingCType(),
8944 I->getLayoutCompatible(),
8945 I->getMustBeNull());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008946 }
Richard Smith483b9f32011-02-21 20:05:19 +00008947}
8948
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008949Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8950 ArrayRef<Decl *> Group) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00008951 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008952
8953 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00008954 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008955
David Majnemeraa824612013-09-17 23:57:10 +00008956 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008957 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemeraa824612013-09-17 23:57:10 +00008958 if (Decl *D = Group[i]) {
8959 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8960 if (!FirstDeclaratorInGroup)
8961 FirstDeclaratorInGroup = DD;
Richard Smith406c38e2011-02-23 00:37:57 +00008962 Decls.push_back(D);
David Majnemeraa824612013-09-17 23:57:10 +00008963 }
Richard Smith406c38e2011-02-23 00:37:57 +00008964
Eli Friedman5e867c82013-07-10 00:30:46 +00008965 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemeraa824612013-09-17 23:57:10 +00008966 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman5e867c82013-07-10 00:30:46 +00008967 HandleTagNumbering(*this, Tag);
David Majnemeraa824612013-09-17 23:57:10 +00008968 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8969 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8970 }
Eli Friedman5e867c82013-07-10 00:30:46 +00008971 }
David Blaikie66cff722012-11-14 01:52:05 +00008972
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008973 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith406c38e2011-02-23 00:37:57 +00008974}
8975
8976/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8977/// group, performing any necessary semantic checking.
8978Sema::DeclGroupPtrTy
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008979Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith406c38e2011-02-23 00:37:57 +00008980 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00008981 // C++0x [dcl.spec.auto]p7:
8982 // If the type deduced for the template parameter U is not the same in each
8983 // deduction, the program is ill-formed.
8984 // FIXME: When initializer-list support is added, a distinction is needed
8985 // between the deduced type U and the deduced type which 'auto' stands for.
8986 // auto a = 0, b = { 1, 2, 3 };
8987 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008988 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00008989 QualType Deduced;
8990 CanQualType DeducedCanon;
8991 VarDecl *DeducedDecl = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008992 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith34b41d92011-02-20 03:19:35 +00008993 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8994 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00008995 // Don't reissue diagnostics when instantiating a template.
8996 if (AT && D->isInvalidDecl())
8997 break;
Richard Smithdc7a4f52013-04-30 13:56:41 +00008998 QualType U = AT ? AT->getDeducedType() : QualType();
8999 if (!U.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00009000 CanQualType UCanon = Context.getCanonicalType(U);
9001 if (Deduced.isNull()) {
9002 Deduced = U;
9003 DeducedCanon = UCanon;
9004 DeducedDecl = D;
9005 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00009006 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9007 diag::err_auto_different_deductions)
Richard Smithffd015e2013-05-04 04:19:27 +00009008 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith34b41d92011-02-20 03:19:35 +00009009 << Deduced << DeducedDecl->getDeclName()
9010 << U << D->getDeclName()
9011 << DeducedDecl->getInit()->getSourceRange()
9012 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00009013 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00009014 break;
9015 }
9016 }
9017 }
9018 }
9019 }
9020
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009021 ActOnDocumentableDecls(Group);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009022
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009023 return DeclGroupPtrTy::make(
9024 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00009025}
Steve Naroffe1223f72007-08-28 03:03:08 +00009026
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009027void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009028 ActOnDocumentableDecls(D);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009029}
9030
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009031void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009032 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009033 if (Group.empty() || !Group[0])
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009034 return;
9035
9036 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9037 Group[0]->getLocation())
9038 == DiagnosticsEngine::Ignored)
9039 return;
9040
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009041 if (Group.size() >= 2) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009042 // This is a decl group. Normally it will contain only declarations
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009043 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009044 // additional declaration references:
9045 // 'typedef struct S {} S;'
9046 // 'typedef struct S *S;'
9047 // 'struct S *pS;'
9048 // FinalizeDeclaratorGroup adds these as separate declarations.
9049 Decl *MaybeTagDecl = Group[0];
9050 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009051 Group = Group.slice(1);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009052 }
9053 }
9054
9055 // See if there are any new comments that are not attached to a decl.
9056 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9057 if (!Comments.empty() &&
9058 !Comments.back()->isAttached()) {
9059 // There is at least one comment that not attached to a decl.
9060 // Maybe it should be attached to one of these decls?
9061 //
9062 // Note that this way we pick up not only comments that precede the
9063 // declaration, but also comments that *follow* the declaration -- thanks to
9064 // the lookahead in the lexer: we've consumed the semicolon and looked
9065 // ahead through comments.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009066 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko19523542012-09-29 11:40:46 +00009067 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009068 }
9069}
Chris Lattner682bf922009-03-29 16:50:03 +00009070
Chris Lattner04421082008-04-08 04:40:51 +00009071/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9072/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00009073Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00009074 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00009075
Chris Lattner04421082008-04-08 04:40:51 +00009076 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Valifad9e132013-09-26 19:54:12 +00009077
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009078 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00009079 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009080 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00009081 StorageClass = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00009082 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009083 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9084 StorageClass = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009085 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00009086 Diag(DS.getStorageClassSpecLoc(),
9087 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00009088 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00009089 }
Eli Friedman63054b32009-04-19 20:27:55 +00009090
Richard Smithec642442013-04-12 22:46:28 +00009091 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9092 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9093 << DeclSpec::getSpecifierName(TSCS);
9094 if (DS.isConstexprSpecified())
9095 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smithaf1fc7a2011-08-15 21:04:07 +00009096 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00009097
Richard Smithec642442013-04-12 22:46:28 +00009098 DiagnoseFunctionSpecifiers(DS);
Eli Friedman85a53192009-04-07 19:37:57 +00009099
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00009100 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00009101 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009102
David Blaikie4e4d0842012-03-11 07:00:24 +00009103 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009104 // Check that there are no default arguments inside the type of this
9105 // parameter.
9106 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009107
9108 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9109 if (D.getCXXScopeSpec().isSet()) {
9110 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9111 << D.getCXXScopeSpec().getRange();
9112 D.getCXXScopeSpec().clear();
9113 }
Douglas Gregor402abb52009-05-28 23:31:59 +00009114 }
9115
Sean Hunt7533a5b2010-11-03 01:07:06 +00009116 // Ensure we have a valid name
9117 IdentifierInfo *II = 0;
9118 if (D.hasName()) {
9119 II = D.getIdentifier();
9120 if (!II) {
9121 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9122 << GetNameForDeclarator(D).getName().getAsString();
9123 D.setInvalidType(true);
9124 }
9125 }
9126
Chris Lattnerd84aac12010-02-22 00:40:25 +00009127 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00009128 if (II) {
John McCall10f28732010-03-18 06:42:38 +00009129 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9130 ForRedeclaration);
9131 LookupName(R, S);
9132 if (R.isSingleResult()) {
9133 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00009134 if (PrevDecl->isTemplateParameter()) {
9135 // Maybe we will complain about the shadowed template parameter.
9136 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9137 // Just pretend that we didn't see the previous declaration.
9138 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00009139 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00009140 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00009141 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00009142
Chris Lattnercf79b012009-01-21 02:38:50 +00009143 // Recover by removing the name
9144 II = 0;
9145 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009146 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00009147 }
Chris Lattner04421082008-04-08 04:40:51 +00009148 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009149 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00009150
John McCall7a9813c2010-01-22 00:28:27 +00009151 // Temporarily put parameter variables in the translation unit, not
9152 // the enclosing context. This prevents them from accidentally
9153 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009154 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00009155 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009156 D.getIdentifierLoc(), II,
9157 parmDeclType, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009158 StorageClass);
Mike Stump1eb44332009-09-09 15:08:12 +00009159
Chris Lattnereaaebc72009-04-25 08:06:05 +00009160 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00009161 New->setInvalidDecl();
9162
9163 assert(S->isFunctionPrototypeScope());
9164 assert(S->getFunctionPrototypeDepth() >= 1);
9165 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9166 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009167
Douglas Gregor44b43212008-12-11 16:49:14 +00009168 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00009169 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009170 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00009171 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00009172
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009173 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00009174
Douglas Gregore3895852011-09-12 18:37:38 +00009175 if (D.getDeclSpec().isModulePrivateSpecified())
9176 Diag(New->getLocation(), diag::err_module_private_local)
9177 << 1 << New->getDeclName()
9178 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9179 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9180
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009181 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00009182 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9183 }
John McCalld226f652010-08-21 09:40:31 +00009184 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00009185}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00009186
John McCall82dc0092010-06-04 11:21:44 +00009187/// \brief Synthesizes a variable for a parameter arising from a
9188/// typedef.
9189ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9190 SourceLocation Loc,
9191 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009192 /* FIXME: setting StartLoc == Loc.
9193 Would it be worth to modify callers so as to provide proper source
9194 location for the unnamed parameters, embedding the parameter's type? */
9195 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00009196 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009197 SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00009198 Param->setImplicit();
9199 return Param;
9200}
9201
John McCallfbce0e12010-08-24 09:05:15 +00009202void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9203 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00009204 // Don't diagnose unused-parameter errors in template instantiations; we
9205 // will already have done so in the template itself.
9206 if (!ActiveTemplateInstantiations.empty())
9207 return;
9208
9209 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00009210 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00009211 !(*Param)->hasAttr<UnusedAttr>()) {
9212 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9213 << (*Param)->getDeclName();
9214 }
9215 }
9216}
9217
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009218void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9219 ParmVarDecl * const *ParamEnd,
9220 QualType ReturnTy,
9221 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009222 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009223 return;
9224
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009225 // Warn if the return value is pass-by-value and larger than the specified
9226 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00009227 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009228 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009229 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009230 Diag(D->getLocation(), diag::warn_return_value_size)
9231 << D->getDeclName() << Size;
9232 }
9233
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009234 // Warn if any parameter is pass-by-value and larger than the specified
9235 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009236 for (; Param != ParamEnd; ++Param) {
9237 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00009238 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009239 continue;
9240 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009241 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009242 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9243 << (*Param)->getDeclName() << Size;
9244 }
9245}
9246
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009247ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9248 SourceLocation NameLoc, IdentifierInfo *Name,
9249 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009250 VarDecl::StorageClass StorageClass) {
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009251 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00009252 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009253 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009254 T->isObjCLifetimeType()) {
9255
9256 Qualifiers::ObjCLifetime lifetime;
9257
9258 // Special cases for arrays:
9259 // - if it's const, use __unsafe_unretained
9260 // - otherwise, it's an error
9261 if (T->isArrayType()) {
9262 if (!T.isConstQualified()) {
9263 DelayedDiagnostics.add(
9264 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanian175fb102011-10-03 22:11:57 +00009265 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009266 }
9267 lifetime = Qualifiers::OCL_ExplicitNone;
9268 } else {
9269 lifetime = T->getObjCARCImplicitLifetime();
9270 }
9271 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCallf85e1932011-06-15 23:02:42 +00009272 }
9273
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009274 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00009275 Context.getAdjustedParameterType(T),
9276 TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009277 StorageClass, 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009278
9279 // Parameters can not be abstract class types.
9280 // For record types, this is done by the AbstractClassUsageDiagnoser once
9281 // the class has been completely parsed.
9282 if (!CurContext->isRecord() &&
9283 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9284 AbstractParamType))
9285 New->setInvalidDecl();
9286
9287 // Parameter declarators cannot be interface types. All ObjC objects are
9288 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00009289 if (T->isObjCObjectType()) {
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009290 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009291 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009292 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009293 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009294 T = Context.getObjCObjectPointerType(T);
9295 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009296 }
9297
9298 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9299 // duration shall not be qualified by an address-space qualifier."
9300 // Since all parameters have automatic store duration, they can not have
9301 // an address space.
9302 if (T.getAddressSpace() != 0) {
9303 Diag(NameLoc, diag::err_arg_with_address_space);
9304 New->setInvalidDecl();
9305 }
9306
9307 return New;
9308}
9309
Douglas Gregora3a83512009-04-01 23:51:29 +00009310void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9311 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009312 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00009313
Reid Spencer5f016e22007-07-11 17:01:13 +00009314 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9315 // for a K&R function.
9316 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00009317 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9318 --i;
Chris Lattner04421082008-04-08 04:40:51 +00009319 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009320 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009321 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009322 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009323 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00009324 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00009325 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00009326 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00009327
Reid Spencer5f016e22007-07-11 17:01:13 +00009328 // Implicitly declare the argument as type 'int' for lack of a better
9329 // type.
John McCall0b7e6782011-03-24 11:26:52 +00009330 AttributeFactory attrs;
9331 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00009332 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00009333 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00009334 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00009335 PrevSpec, DiagID);
Abramo Bagnara16467f22012-10-04 21:38:29 +00009336 // Use the identifier location for the type source range.
9337 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9338 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattner04421082008-04-08 04:40:51 +00009339 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9340 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00009341 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00009342 }
9343 }
Mike Stump1eb44332009-09-09 15:08:12 +00009344 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00009345}
9346
Richard Smith87162c22012-04-17 22:30:01 +00009347Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00009348 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009349 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00009350 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00009351
Douglas Gregor45fa5602011-11-07 20:56:01 +00009352 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009353 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner682bf922009-03-29 16:50:03 +00009354 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00009355}
9356
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009357static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9358 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009359 // Don't warn about invalid declarations.
9360 if (FD->isInvalidDecl())
9361 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009362
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009363 // Or declarations that aren't global.
9364 if (!FD->isGlobal())
9365 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009366
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009367 // Don't warn about C++ member functions.
9368 if (isa<CXXMethodDecl>(FD))
9369 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009370
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009371 // Don't warn about 'main'.
9372 if (FD->isMain())
9373 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009374
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009375 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00009376 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009377 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009378
9379 // Don't warn about function templates.
9380 if (FD->getDescribedFunctionTemplate())
9381 return false;
9382
9383 // Don't warn about function template specializations.
9384 if (FD->isFunctionTemplateSpecialization())
9385 return false;
9386
Tanya Lattnera95b4f72012-07-26 00:08:28 +00009387 // Don't warn for OpenCL kernels.
9388 if (FD->hasAttr<OpenCLKernelAttr>())
9389 return false;
Richard Smitha41c97a2013-09-20 01:15:31 +00009390
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009391 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00009392 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9393 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009394 // Ignore any declarations that occur in function or method
9395 // scope, because they aren't visible from the header.
Richard Smitha41c97a2013-09-20 01:15:31 +00009396 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009397 continue;
Richard Smitha41c97a2013-09-20 01:15:31 +00009398
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009399 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009400 if (FD->getNumParams() == 0)
9401 PossibleZeroParamPrototype = Prev;
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009402 break;
9403 }
Richard Smitha41c97a2013-09-20 01:15:31 +00009404
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009405 return MissingPrototype;
9406}
9407
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009408void
9409Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9410 const FunctionDecl *EffectiveDefinition) {
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009411 // Don't complain if we're in GNU89 mode and the previous definition
9412 // was an extern inline function.
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009413 const FunctionDecl *Definition = EffectiveDefinition;
9414 if (!Definition)
9415 if (!FD->isDefined(Definition))
9416 return;
9417
9418 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009419 return;
9420
9421 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9422 Definition->getStorageClass() == SC_Extern)
9423 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00009424 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009425 else
9426 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9427
9428 Diag(Definition->getLocation(), diag::note_previous_definition);
9429 FD->setInvalidDecl();
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009430}
Faisal Valibef582b2013-10-23 16:10:50 +00009431static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9432 Sema &S) {
9433 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9434 S.PushLambdaScope();
9435 LambdaScopeInfo *LSI = S.getCurLambda();
9436 LSI->CallOperator = CallOperator;
9437 LSI->Lambda = LambdaClass;
9438 LSI->ReturnType = CallOperator->getResultType();
9439 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9440
9441 if (LCD == LCD_None)
9442 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9443 else if (LCD == LCD_ByCopy)
9444 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9445 else if (LCD == LCD_ByRef)
9446 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9447 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9448
9449 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9450 LSI->Mutable = !CallOperator->isConst();
9451
9452 // FIXME: Add the captures to the LSI.
9453}
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009454
John McCalld226f652010-08-21 09:40:31 +00009455Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00009456 // Clear the last template instantiation error context.
9457 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9458
Douglas Gregor52591bf2009-06-24 00:54:41 +00009459 if (!D)
9460 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00009461 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00009462
John McCalld226f652010-08-21 09:40:31 +00009463 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00009464 FD = FunTmpl->getTemplatedDecl();
9465 else
John McCalld226f652010-08-21 09:40:31 +00009466 FD = cast<FunctionDecl>(D);
Faisal Valifad9e132013-09-26 19:54:12 +00009467 // If we are instantiating a generic lambda call operator, push
9468 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valibef582b2013-10-23 16:10:50 +00009469 // that's already been calculated (ActOnLambdaExpr) to prime the current
9470 // LambdaScopeInfo.
9471 // When the template operator is being specialized, the LambdaScopeInfo,
9472 // has to be properly restored so that tryCaptureVariable doesn't try
9473 // and capture any new variables. In addition when calculating potential
9474 // captures during transformation of nested lambdas, it is necessary to
9475 // have the LSI properly restored.
Faisal Vali998c5182013-09-29 20:15:45 +00009476 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Valifad9e132013-09-26 19:54:12 +00009477 assert(ActiveTemplateInstantiations.size() &&
9478 "There should be an active template instantiation on the stack "
9479 "when instantiating a generic lambda!");
Faisal Valibef582b2013-10-23 16:10:50 +00009480 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Valifad9e132013-09-26 19:54:12 +00009481 }
9482 else
9483 // Enter a new function scope
9484 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00009485
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009486 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009487 if (!FD->isLateTemplateParsed())
9488 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009489
Douglas Gregorcda9c672009-02-16 17:45:42 +00009490 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009491 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindolaad24ad42013-06-13 18:34:17 +00009492 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9493 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00009494 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00009495 FD->setInvalidDecl();
9496 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00009497 }
9498
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009499 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00009500 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9501 QualType ResultType = FD->getResultType();
9502 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00009503 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00009504 RequireCompleteType(FD->getLocation(), ResultType,
9505 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009506 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009507
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009508 // GNU warning -Wmissing-prototypes:
9509 // Warn if a global function is defined without a previous
9510 // prototype declaration. This warning is issued even if the
9511 // definition itself provides a prototype. The aim is to detect
9512 // global functions that fail to be declared in header files.
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009513 const FunctionDecl *PossibleZeroParamPrototype = 0;
9514 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009515 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithac83a3c2013-06-25 20:34:17 +00009516
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009517 if (PossibleZeroParamPrototype) {
Richard Smithac83a3c2013-06-25 20:34:17 +00009518 // We found a declaration that is not a prototype,
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009519 // but that could be a zero-parameter prototype
Richard Smithac83a3c2013-06-25 20:34:17 +00009520 if (TypeSourceInfo *TI =
9521 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9522 TypeLoc TL = TI->getTypeLoc();
9523 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9524 Diag(PossibleZeroParamPrototype->getLocation(),
9525 diag::note_declaration_not_a_prototype)
9526 << PossibleZeroParamPrototype
9527 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9528 }
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009529 }
9530 }
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009531
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009532 if (FnBodyScope)
9533 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009534
Chris Lattner04421082008-04-08 04:40:51 +00009535 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00009536 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9537 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00009538
9539 // Introduce our parameters into the function scope
9540 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9541 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00009542 Param->setOwningFunction(FD);
9543
Chris Lattner04421082008-04-08 04:40:51 +00009544 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009545 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009546 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00009547
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009548 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00009549 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009550 }
Chris Lattner04421082008-04-08 04:40:51 +00009551
James Molloy16f1f712012-02-29 10:24:19 +00009552 // If we had any tags defined in the function prototype,
9553 // introduce them into the function scope.
9554 if (FnBodyScope) {
Robert Wilhelm834c0582013-08-09 18:02:13 +00009555 for (ArrayRef<NamedDecl *>::iterator
9556 I = FD->getDeclsInPrototypeScope().begin(),
9557 E = FD->getDeclsInPrototypeScope().end();
9558 I != E; ++I) {
James Molloy16f1f712012-02-29 10:24:19 +00009559 NamedDecl *D = *I;
9560
9561 // Some of these decls (like enums) may have been pinned to the translation unit
9562 // for lack of a real context earlier. If so, remove from the translation unit
9563 // and reattach to the current context.
9564 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9565 // Is the decl actually in the context?
9566 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9567 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9568 if (*DI == D) {
9569 Context.getTranslationUnitDecl()->removeDecl(D);
9570 break;
9571 }
9572 }
9573 // Either way, reassign the lexical decl context to our FunctionDecl.
9574 D->setLexicalDeclContext(CurContext);
9575 }
9576
9577 // If the decl has a non-null name, make accessible in the current scope.
9578 if (!D->getName().empty())
9579 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9580
9581 // Similarly, dive into enums and fish their constants out, making them
9582 // accessible in this scope.
9583 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9584 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9585 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie581deb32012-06-06 20:45:41 +00009586 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy16f1f712012-02-29 10:24:19 +00009587 }
9588 }
9589 }
9590
Richard Smith87162c22012-04-17 22:30:01 +00009591 // Ensure that the function's exception specification is instantiated.
9592 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9593 ResolveExceptionSpec(D->getLocation(), FPT);
9594
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009595 // Checking attributes of current function definition
9596 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00009597 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9598 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9599 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00009600 // Microsoft accepts dllimport for functions defined within class scope.
9601 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00009602 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009603 Diag(FD->getLocation(),
9604 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9605 << "dllimport";
9606 FD->setInvalidDecl();
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009607 return D;
Ted Kremenek12911a82010-02-21 05:12:53 +00009608 }
9609
9610 // Visual C++ appears to not think this is an issue, so only issue
9611 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009612 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009613 // If a symbol previously declared dllimport is later defined, the
9614 // attribute is ignored in subsequent references, and a warning is
9615 // emitted.
9616 Diag(FD->getLocation(),
9617 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00009618 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009619 }
9620 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +00009621 // We want to attach documentation to original Decl (which might be
9622 // a function template).
9623 ActOnDocumentableDecl(D);
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009624 return D;
Reid Spencer5f016e22007-07-11 17:01:13 +00009625}
9626
Douglas Gregor5077c382010-05-15 06:01:05 +00009627/// \brief Given the set of return statements within a function body,
9628/// compute the variables that are subject to the named return value
9629/// optimization.
9630///
9631/// Each of the variables that is subject to the named return value
9632/// optimization will be marked as NRVO variables in the AST, and any
9633/// return statement that has a marked NRVO variable as its NRVO candidate can
9634/// use the named return value optimization.
9635///
9636/// This function applies a very simplistic algorithm for NRVO: if every return
9637/// statement in the function has the same NRVO candidate, that candidate is
9638/// the NRVO variable.
9639///
9640/// FIXME: Employ a smarter algorithm that accounts for multiple return
9641/// statements and the lifetimes of the NRVO candidates. We should be able to
9642/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009643void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00009644 ReturnStmt **Returns = Scope->Returns.data();
9645
Douglas Gregor5077c382010-05-15 06:01:05 +00009646 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00009647 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00009648 if (!Returns[I]->getNRVOCandidate())
9649 return;
9650
9651 if (!NRVOCandidate)
9652 NRVOCandidate = Returns[I]->getNRVOCandidate();
9653 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9654 return;
9655 }
9656
9657 if (NRVOCandidate)
9658 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9659}
9660
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009661bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smithd1bac8d2012-11-27 21:31:01 +00009662 if (!Consumer.shouldSkipFunctionBody(D))
9663 return false;
9664
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009665 if (isa<ObjCMethodDecl>(D))
9666 return true;
9667
9668 FunctionDecl *FD = 0;
9669 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9670 FD = FTD->getTemplatedDecl();
9671 else
9672 FD = cast<FunctionDecl>(D);
9673
9674 // We cannot skip the body of a function (or function template) which is
9675 // constexpr, since we may need to evaluate its body in order to parse the
9676 // rest of the file.
Richard Smith25d8c852013-05-10 04:31:10 +00009677 // We cannot skip the body of a function with an undeduced return type,
9678 // because any callers of that function need to know the type.
9679 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009680}
9681
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009682Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009683 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009684 FD->setHasSkippedBody();
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009685 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009686 MD->setHasSkippedBody();
9687 return ActOnFinishFunctionBody(Decl, 0);
9688}
9689
John McCallf312b1e2010-08-26 23:41:50 +00009690Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009691 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009692}
9693
John McCall9ae2f072010-08-23 23:25:46 +00009694Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9695 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00009696 FunctionDecl *FD = 0;
9697 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9698 if (FunTmpl)
9699 FD = FunTmpl->getTemplatedDecl();
9700 else
9701 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9702
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009703 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009704 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009705
Douglas Gregord83d0402009-08-22 00:34:47 +00009706 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00009707 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00009708
Richard Smith25d8c852013-05-10 04:31:10 +00009709 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9710 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9711 // If the function has a deduced result type but contains no 'return'
9712 // statements, the result type as written must be exactly 'auto', and
9713 // the deduced result type is 'void'.
9714 if (!FD->getResultType()->getAs<AutoType>()) {
9715 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9716 << FD->getResultType();
9717 FD->setInvalidDecl();
9718 } else {
9719 // Substitute 'void' for the 'auto' in the type.
9720 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9721 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9722 Context.adjustDeducedFunctionResultType(
9723 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith60e141e2013-05-04 07:00:32 +00009724 }
9725 }
9726
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009727 // The only way to be included in UndefinedButUsed is if there is an
9728 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewycky995e26b2013-01-31 03:23:57 +00009729 // is the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00009730 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00009731 if (!FD->isExternallyVisible())
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009732 UndefinedButUsed.erase(FD);
9733 else if (FD->isInlined() &&
9734 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9735 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9736 UndefinedButUsed.erase(FD);
9737 }
Nick Lewycky995e26b2013-01-31 03:23:57 +00009738
John McCall75d8ba32012-02-14 19:50:52 +00009739 // If the function implicitly returns zero (like 'main') or is naked,
9740 // don't complain about missing return statements.
9741 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009742 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00009743
Francois Pichet6a247472011-05-11 02:14:46 +00009744 // MSVC permits the use of pure specifier (=0) on function definition,
9745 // defined at class scope, warn about this non standard construct.
Reid Kleckner5dbed662013-10-08 22:45:29 +00009746 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet6a247472011-05-11 02:14:46 +00009747 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9748
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009749 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009750 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009751 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9752 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009753
9754 // If this is a constructor, we need a vtable.
9755 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9756 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00009757
Jordan Rose7dd900e2012-07-02 21:19:23 +00009758 // Try to apply the named return value optimization. We have to check
9759 // if we can do this here because lambdas keep return statements around
9760 // to deduce an implicit return type.
9761 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9762 !FD->isDependentContext())
9763 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009764 }
9765
Douglas Gregor76e3da52012-02-08 20:17:14 +00009766 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9767 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00009768 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00009769 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00009770 MD->setBody(Body);
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009771 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009772 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009773 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9774 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00009775
9776 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009777 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009778 }
Jordan Rose535a5d02012-10-19 16:05:26 +00009779 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanian9f559832012-09-10 16:51:09 +00009780 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9781 << MD->getSelector().getAsString();
Jordan Rose535a5d02012-10-19 16:05:26 +00009782 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00009783 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00009784 } else {
John McCalld226f652010-08-21 09:40:31 +00009785 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00009786 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009787
Jordan Rose535a5d02012-10-19 16:05:26 +00009788 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman95aac152012-08-01 21:02:59 +00009789 "This should only be set for ObjC methods, which should have been "
9790 "handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00009791
Reid Spencer5f016e22007-07-11 17:01:13 +00009792 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009793 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009794 // C++ constructors that have function-try-blocks can't have return
9795 // statements in the handlers of that block. (C++ [except.handle]p14)
9796 // Verify this.
9797 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9798 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9799
Richard Smith37bee672011-08-12 18:44:32 +00009800 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00009801 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00009802 !dcl->isInvalidDecl() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009803 !hasAnyUnrecoverableErrorsInThisFunction() &&
9804 !PP.isCodeCompletionEnabled())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009805 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00009806
John McCall15442822010-08-04 01:04:25 +00009807 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9808 if (!Destructor->getParent()->isDependentType())
9809 CheckDestructor(Destructor);
9810
John McCallef027fe2010-03-16 21:39:52 +00009811 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9812 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00009813 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009814
9815 // If any errors have occurred, clear out any temporaries that may have
9816 // been leftover. This ensures that these temporaries won't be picked up for
9817 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00009818 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00009819 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00009820 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00009821 }
9822 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9823 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009824 // Since the body is valid, issue any analysis-based warnings that are
9825 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009826 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009827 }
9828
Richard Smith86c3ae42012-02-13 03:54:03 +00009829 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9830 (!CheckConstexprFunctionDecl(FD) ||
9831 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00009832 FD->setInvalidDecl();
9833
John McCall80ee6e82011-11-10 05:35:25 +00009834 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00009835 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00009836 assert(MaybeODRUseExprs.empty() &&
9837 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009838 }
9839
John McCall90f97892010-03-25 22:08:03 +00009840 if (!IsInstantiation)
9841 PopDeclContext();
9842
Eli Friedmanec9ea722012-01-05 03:35:19 +00009843 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregord5b57282009-11-15 07:07:58 +00009844 // If any errors have occurred, clear out any temporaries that may have
9845 // been leftover. This ensures that these temporaries won't be picked up for
9846 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00009847 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00009848 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00009849 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00009850
John McCalld226f652010-08-21 09:40:31 +00009851 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00009852}
9853
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009854
9855/// When we finish delayed parsing of an attribute, we must attach it to the
9856/// relevant Decl.
9857void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9858 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00009859 // Always attach attributes to the underlying decl.
9860 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9861 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00009862 ProcessDeclAttributeList(S, D, Attrs.getList());
9863
9864 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9865 if (Method->isStatic())
9866 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009867}
9868
9869
Reid Spencer5f016e22007-07-11 17:01:13 +00009870/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9871/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00009872NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00009873 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00009874 // Before we produce a declaration for an implicitly defined
9875 // function, see whether there was a locally-scoped declaration of
9876 // this name as a function or variable. If so, use that
9877 // (non-visible) declaration, and complain about it.
Richard Smith662f41b2013-06-18 20:15:12 +00009878 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9879 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9880 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9881 return ExternCPrev;
Douglas Gregor63935192009-03-02 00:19:53 +00009882 }
9883
Chris Lattner37d10842008-05-05 21:18:06 +00009884 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009885 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009886 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00009887 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00009888 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009889 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00009890 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009891 diag_id = diag::warn_implicit_function_decl;
9892 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00009893
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009894 // Because typo correction is expensive, only do it if the implicit
9895 // function declaration is going to be treated as an error.
9896 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9897 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00009898 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009899 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smith2d670972013-08-17 00:46:16 +00009900 LookupOrdinaryName, S, 0, Validator)))
9901 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9902 /*ErrorRecovery*/false);
Hans Wennborg122de3e2011-12-06 09:46:12 +00009903 }
9904
Reid Spencer5f016e22007-07-11 17:01:13 +00009905 // Set a Declarator for the implicit definition: int foo();
9906 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00009907 AttributeFactory attrFactory;
9908 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00009909 unsigned DiagID;
9910 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00009911 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00009912 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009913 SourceLocation NoLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009914 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009915 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9916 /*IsAmbiguous=*/false,
9917 /*RParenLoc=*/NoLoc,
9918 /*ArgInfo=*/0,
9919 /*NumArgs=*/0,
9920 /*EllipsisLoc=*/NoLoc,
9921 /*RParenLoc=*/NoLoc,
9922 /*TypeQuals=*/0,
9923 /*RefQualifierIsLvalueRef=*/true,
9924 /*RefQualifierLoc=*/NoLoc,
9925 /*ConstQualifierLoc=*/NoLoc,
9926 /*VolatileQualifierLoc=*/NoLoc,
9927 /*MutableLoc=*/NoLoc,
9928 EST_None,
9929 /*ESpecLoc=*/NoLoc,
9930 /*Exceptions=*/0,
9931 /*ExceptionRanges=*/0,
9932 /*NumExceptions=*/0,
9933 /*NoexceptExpr=*/0,
9934 Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00009935 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00009936 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00009937 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00009938
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009939 // Insert this function into translation-unit scope.
9940
9941 DeclContext *PrevDC = CurContext;
9942 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009943
Jordan Rose41f3f3a2013-03-05 01:27:54 +00009944 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00009945 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009946
9947 CurContext = PrevDC;
9948
Douglas Gregor3c385e52009-02-14 18:57:46 +00009949 AddKnownFunctionAttributes(FD);
9950
Steve Naroffe2ef8152008-04-04 14:32:09 +00009951 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009952}
9953
Douglas Gregor3c385e52009-02-14 18:57:46 +00009954/// \brief Adds any function attributes that we know a priori based on
9955/// the declaration of this function.
9956///
9957/// These attributes can apply both to implicitly-declared builtins
9958/// (like __builtin___printf_chk) or to library-declared functions
9959/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009960///
9961/// We need to check for duplicate attributes both here and where user-written
9962/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +00009963void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9964 if (FD->isInvalidDecl())
9965 return;
9966
9967 // If this is a built-in function, map its builtin attributes to
9968 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009969 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00009970 // Handle printf-formatting attributes.
9971 unsigned FormatIdx;
9972 bool HasVAListArg;
9973 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009974 if (!FD->getAttr<FormatAttr>()) {
9975 const char *fmt = "printf";
9976 unsigned int NumParams = FD->getNumParams();
9977 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
9978 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
9979 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +00009980 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00009981 &Context.Idents.get(fmt),
9982 FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00009983 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009984 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00009985 }
Ted Kremenekbee05c12010-07-16 02:11:15 +00009986 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
9987 HasVAListArg)) {
9988 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00009989 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00009990 &Context.Idents.get("scanf"),
9991 FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +00009992 HasVAListArg ? 0 : FormatIdx+2));
9993 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009994
9995 // Mark const if we don't care about errno and that is the only
9996 // thing preventing the function from being const. This allows
9997 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +00009998 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00009999 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010000 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010001 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010002 }
Mike Stump0feecbb2009-07-27 19:14:18 +000010003
Rafael Espindola67004152011-10-12 19:51:18 +000010004 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10005 !FD->getAttr<ReturnsTwiceAttr>())
10006 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010007 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010008 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010009 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010010 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +000010011 }
10012
10013 IdentifierInfo *Name = FD->getIdentifier();
10014 if (!Name)
10015 return;
David Blaikie4e4d0842012-03-11 07:00:24 +000010016 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +000010017 FD->getDeclContext()->isTranslationUnit()) ||
10018 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +000010019 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +000010020 LinkageSpecDecl::lang_c)) {
10021 // Okay: this could be a libc/libm/Objective-C function we know
10022 // about.
10023 } else
10024 return;
10025
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010026 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +000010027 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +000010028 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010029 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010030 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010031 &Context.Idents.get("printf"), 2,
Eli Friedmand7dad722009-06-10 04:01:38 +000010032 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +000010033 }
Jordan Rose8a64f882012-08-08 21:17:31 +000010034
10035 if (Name->isStr("__CFStringMakeConstantString")) {
10036 // We already have a __builtin___CFStringMakeConstantString,
10037 // but builds that use -fno-constant-cfstrings don't go through that.
10038 if (!FD->getAttr<FormatArgAttr>())
10039 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10040 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010041}
Reid Spencer5f016e22007-07-11 17:01:13 +000010042
John McCallba6a9bd2009-10-24 08:00:42 +000010043TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000010044 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010045 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +000010046 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +000010047
John McCalla93c9342009-12-07 02:54:59 +000010048 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +000010049 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +000010050 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +000010051 }
10052
Reid Spencer5f016e22007-07-11 17:01:13 +000010053 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +000010054 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010055 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +000010056 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +000010057 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +000010058 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +000010059
John McCallcde5a402011-02-01 08:20:08 +000010060 // Bail out immediately if we have an invalid declaration.
10061 if (D.isInvalidType()) {
10062 NewTD->setInvalidDecl();
10063 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +000010064 }
10065
Douglas Gregore3895852011-09-12 18:37:38 +000010066 if (D.getDeclSpec().isModulePrivateSpecified()) {
10067 if (CurContext->isFunctionOrMethod())
10068 Diag(NewTD->getLocation(), diag::err_module_private_local)
10069 << 2 << NewTD->getDeclName()
10070 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10071 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10072 else
10073 NewTD->setModulePrivate();
10074 }
Douglas Gregor8d267c52011-09-09 02:06:17 +000010075
John McCallcde5a402011-02-01 08:20:08 +000010076 // C++ [dcl.typedef]p8:
10077 // If the typedef declaration defines an unnamed class (or
10078 // enum), the first typedef-name declared by the declaration
10079 // to be that class type (or enum type) is used to denote the
10080 // class type (or enum type) for linkage purposes only.
10081 // We need to check whether the type was declared in the declaration.
10082 switch (D.getDeclSpec().getTypeSpecType()) {
10083 case TST_enum:
10084 case TST_struct:
Joao Matos6666ed42012-08-31 18:45:21 +000010085 case TST_interface:
John McCallcde5a402011-02-01 08:20:08 +000010086 case TST_union:
10087 case TST_class: {
10088 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10089
10090 // Do nothing if the tag is not anonymous or already has an
10091 // associated typedef (from an earlier typedef in this decl group).
10092 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +000010093 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +000010094
10095 // A well-formed anonymous tag must always be a TUK_Definition.
10096 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10097
10098 // The type must match the tag exactly; no qualifiers allowed.
10099 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10100 break;
10101
10102 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +000010103 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +000010104 break;
10105 }
10106
10107 default:
10108 break;
10109 }
10110
Steve Naroff5912a352007-08-28 20:14:24 +000010111 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +000010112}
10113
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010114
Richard Smithf1c66b42012-03-14 23:13:10 +000010115/// \brief Check that this is a valid underlying type for an enum declaration.
10116bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10117 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10118 QualType T = TI->getType();
10119
Eli Friedman2fcff832012-12-18 02:37:32 +000010120 if (T->isDependentType())
Richard Smithf1c66b42012-03-14 23:13:10 +000010121 return false;
10122
Eli Friedman2fcff832012-12-18 02:37:32 +000010123 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10124 if (BT->isInteger())
10125 return false;
10126
Richard Smithf1c66b42012-03-14 23:13:10 +000010127 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10128 return true;
10129}
10130
10131/// Check whether this is a valid redeclaration of a previous enumeration.
10132/// \return true if the redeclaration was invalid.
10133bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10134 QualType EnumUnderlyingTy,
10135 const EnumDecl *Prev) {
10136 bool IsFixed = !EnumUnderlyingTy.isNull();
10137
10138 if (IsScoped != Prev->isScoped()) {
10139 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10140 << Prev->isScoped();
10141 Diag(Prev->getLocation(), diag::note_previous_use);
10142 return true;
10143 }
10144
10145 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +000010146 if (!EnumUnderlyingTy->isDependentType() &&
10147 !Prev->getIntegerType()->isDependentType() &&
10148 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +000010149 Prev->getIntegerType())) {
10150 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10151 << EnumUnderlyingTy << Prev->getIntegerType();
10152 Diag(Prev->getLocation(), diag::note_previous_use);
10153 return true;
10154 }
10155 } else if (IsFixed != Prev->isFixed()) {
10156 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10157 << Prev->isFixed();
10158 Diag(Prev->getLocation(), diag::note_previous_use);
10159 return true;
10160 }
10161
10162 return false;
10163}
10164
Joao Matos6666ed42012-08-31 18:45:21 +000010165/// \brief Get diagnostic %select index for tag kind for
10166/// redeclaration diagnostic message.
10167/// WARNING: Indexes apply to particular diagnostics only!
10168///
10169/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +000010170static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +000010171 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +000010172 case TTK_Struct: return 0;
10173 case TTK_Interface: return 1;
10174 case TTK_Class: return 2;
10175 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +000010176 }
Joao Matos6666ed42012-08-31 18:45:21 +000010177}
10178
10179/// \brief Determine if tag kind is a class-key compatible with
10180/// class for redeclaration (class, struct, or __interface).
10181///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000010182/// \returns true iff the tag kind is compatible.
Joao Matos6666ed42012-08-31 18:45:21 +000010183static bool isClassCompatTagKind(TagTypeKind Tag)
10184{
10185 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10186}
10187
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010188/// \brief Determine whether a tag with a given kind is acceptable
10189/// as a redeclaration of the given tag declaration.
10190///
10191/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +000010192bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +000010193 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010194 SourceLocation NewTagLoc,
10195 const IdentifierInfo &Name) {
10196 // C++ [dcl.type.elab]p3:
10197 // The class-key or enum keyword present in the
10198 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010199 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010200 // refers. This rule also applies to the form of
10201 // elaborated-type-specifier that declares a class-name or
10202 // friend class since it can be construed as referring to the
10203 // definition of the class. Thus, in any
10204 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010205 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010206 // used to refer to a union (clause 9), and either the class or
10207 // struct class-key shall be used to refer to a class (clause 9)
10208 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010209 TagTypeKind OldTag = Previous->getTagKind();
Joao Matos6666ed42012-08-31 18:45:21 +000010210 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieubbf34c02011-06-10 03:11:26 +000010211 if (OldTag == NewTag)
10212 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010213
Joao Matos6666ed42012-08-31 18:45:21 +000010214 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010215 // Warn about the struct/class tag mismatch.
10216 bool isTemplate = false;
10217 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10218 isTemplate = Record->getDescribedClassTemplate();
10219
Richard Trieubbf34c02011-06-10 03:11:26 +000010220 if (!ActiveTemplateInstantiations.empty()) {
10221 // In a template instantiation, do not offer fix-its for tag mismatches
10222 // since they usually mess up the template instead of fixing the problem.
10223 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010224 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10225 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010226 return true;
10227 }
10228
10229 if (isDefinition) {
10230 // On definitions, check previous tags and issue a fix-it for each
10231 // one that doesn't match the current tag.
10232 if (Previous->getDefinition()) {
10233 // Don't suggest fix-its for redefinitions.
10234 return true;
10235 }
10236
10237 bool previousMismatch = false;
10238 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10239 E(Previous->redecls_end()); I != E; ++I) {
10240 if (I->getTagKind() != NewTag) {
10241 if (!previousMismatch) {
10242 previousMismatch = true;
10243 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010244 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10245 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieubbf34c02011-06-10 03:11:26 +000010246 }
10247 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010248 << getRedeclDiagFromTagKind(NewTag)
Richard Trieubbf34c02011-06-10 03:11:26 +000010249 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matos6666ed42012-08-31 18:45:21 +000010250 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieubbf34c02011-06-10 03:11:26 +000010251 }
10252 }
10253 return true;
10254 }
10255
10256 // Check for a previous definition. If current tag and definition
10257 // are same type, do nothing. If no definition, but disagree with
10258 // with previous tag type, give a warning, but no fix-it.
10259 const TagDecl *Redecl = Previous->getDefinition() ?
10260 Previous->getDefinition() : Previous;
10261 if (Redecl->getTagKind() == NewTag) {
10262 return true;
10263 }
10264
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010265 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010266 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10267 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010268 Diag(Redecl->getLocation(), diag::note_previous_use);
10269
10270 // If there is a previous defintion, suggest a fix-it.
10271 if (Previous->getDefinition()) {
10272 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010273 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieubbf34c02011-06-10 03:11:26 +000010274 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matos6666ed42012-08-31 18:45:21 +000010275 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieubbf34c02011-06-10 03:11:26 +000010276 }
10277
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010278 return true;
10279 }
10280 return false;
10281}
10282
Steve Naroff08d92e42007-09-15 18:49:24 +000010283/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +000010284/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +000010285/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +000010286/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +000010287Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +000010288 SourceLocation KWLoc, CXXScopeSpec &SS,
10289 IdentifierInfo *Name, SourceLocation NameLoc,
10290 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010291 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +000010292 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010293 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010294 SourceLocation ScopedEnumKWLoc,
10295 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010296 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010297 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +000010298 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +000010299 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000010300 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +000010301 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010302
Douglas Gregor402abb52009-05-28 23:31:59 +000010303 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010304 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +000010305 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +000010306
Douglas Gregor1fef4e62009-10-07 22:35:40 +000010307 // FIXME: Check explicit specializations more carefully.
10308 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010309 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +000010310
10311 // We only need to do this matching if we have template parameters
10312 // or a scope specifier, which also conveniently avoids this work
10313 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010314 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +000010315 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000010316 if (TemplateParameterList *TemplateParams =
10317 MatchTemplateParametersToScopeSpecifier(
10318 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10319 isExplicitSpecialization, Invalid)) {
Richard Smith725fe0e2013-04-01 21:43:41 +000010320 if (Kind == TTK_Enum) {
10321 Diag(KWLoc, diag::err_enum_template);
10322 return 0;
10323 }
10324
Douglas Gregord85bea22009-09-26 06:47:28 +000010325 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010326 // This is a declaration or definition of a class template (which may
10327 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010328
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010329 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +000010330 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010331
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010332 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +000010333 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010334 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010335 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010336 ModulePrivateLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010337 TemplateParameterLists.size()-1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010338 TemplateParameterLists.data());
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010339 return Result.get();
10340 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +000010341 // The "template<>" header is extraneous.
10342 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010343 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +000010344 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010345 }
Mike Stump1eb44332009-09-09 15:08:12 +000010346 }
10347 }
10348
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010349 // Figure out the underlying type if this a enum declaration. We need to do
10350 // this early, because it's needed to detect if this is an incompatible
10351 // redeclaration.
10352 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10353
10354 if (Kind == TTK_Enum) {
10355 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10356 // No underlying type explicitly specified, or we failed to parse the
10357 // type, default to int.
10358 EnumUnderlying = Context.IntTy.getTypePtr();
10359 else if (UnderlyingType.get()) {
10360 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10361 // integral type; any cv-qualification is ignored.
10362 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +000010363 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010364 EnumUnderlying = TI;
10365
Richard Smithf1c66b42012-03-14 23:13:10 +000010366 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010367 // Recover by falling back to int.
10368 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010369
Richard Smithf1c66b42012-03-14 23:13:10 +000010370 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010371 UPPC_FixedUnderlyingType))
10372 EnumUnderlying = Context.IntTy.getTypePtr();
10373
David Blaikie4e4d0842012-03-11 07:00:24 +000010374 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +000010375 // Microsoft enums are always of int type.
10376 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010377 }
10378
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010379 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010380 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010381 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010382
Chandler Carruth7bf36002010-03-01 21:17:36 +000010383 RedeclarationKind Redecl = ForRedeclaration;
10384 if (TUK == TUK_Friend || TUK == TUK_Reference)
10385 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +000010386
10387 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregord9433522013-06-27 20:42:30 +000010388 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010389 if (Name && SS.isNotEmpty()) {
10390 // We have a nested-name tag ('struct foo::bar').
10391
10392 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010393 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010394 Name = 0;
10395 goto CreateNewDecl;
10396 }
10397
John McCallc4e70192009-09-11 04:59:25 +000010398 // If this is a friend or a reference to a class in a dependent
10399 // context, don't try to make a decl for it.
10400 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10401 DC = computeDeclContext(SS, false);
10402 if (!DC) {
10403 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010404 return 0;
John McCallc4e70192009-09-11 04:59:25 +000010405 }
John McCall77bb1aa2010-05-01 00:40:08 +000010406 } else {
10407 DC = computeDeclContext(SS, true);
10408 if (!DC) {
10409 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10410 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +000010411 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +000010412 }
John McCallc4e70192009-09-11 04:59:25 +000010413 }
10414
John McCall77bb1aa2010-05-01 00:40:08 +000010415 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +000010416 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +000010417
Douglas Gregor1931b442009-02-03 00:34:39 +000010418 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010419 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +000010420 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +000010421
John McCall68263142009-11-18 22:49:29 +000010422 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010423 return 0;
John McCall6e247262009-10-10 05:48:19 +000010424
John McCall68263142009-11-18 22:49:29 +000010425 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010426 // Name lookup did not find anything. However, if the
10427 // nested-name-specifier refers to the current instantiation,
10428 // and that current instantiation has any dependent base
10429 // classes, we might find something at instantiation time: treat
10430 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +000010431 // But this only makes any sense for reference-like lookups.
10432 if (Previous.wasNotFoundInCurrentInstantiation() &&
10433 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010434 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010435 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010436 }
10437
10438 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +000010439 Diag(NameLoc, diag::err_not_tag_in_scope)
10440 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010441 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +000010442 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010443 goto CreateNewDecl;
10444 }
Chris Lattnercf79b012009-01-21 02:38:50 +000010445 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010446 // If this is a named struct, check to see if there was a previous forward
10447 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +000010448 // FIXME: We're looking into outer scopes here, even when we
10449 // shouldn't be. Doing so can result in ambiguities that we
10450 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +000010451 LookupName(Previous, S);
10452
John McCallc96cd7a2013-03-20 01:53:00 +000010453 // When declaring or defining a tag, ignore ambiguities introduced
10454 // by types using'ed into this scope.
Douglas Gregor93b6bce2011-05-09 21:46:33 +000010455 if (Previous.isAmbiguous() &&
10456 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +000010457 LookupResult::Filter F = Previous.makeFilter();
10458 while (F.hasNext()) {
10459 NamedDecl *ND = F.next();
10460 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10461 F.erase();
10462 }
10463 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +000010464 }
John McCallc96cd7a2013-03-20 01:53:00 +000010465
10466 // C++11 [namespace.memdef]p3:
10467 // If the name in a friend declaration is neither qualified nor
10468 // a template-id and the declaration is a function or an
10469 // elaborated-type-specifier, the lookup to determine whether
10470 // the entity has been previously declared shall not consider
10471 // any scopes outside the innermost enclosing namespace.
10472 //
10473 // Does it matter that this should be by scope instead of by
10474 // semantic context?
10475 if (!Previous.empty() && TUK == TUK_Friend) {
10476 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10477 LookupResult::Filter F = Previous.makeFilter();
10478 while (F.hasNext()) {
10479 NamedDecl *ND = F.next();
10480 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregord9433522013-06-27 20:42:30 +000010481 if (DC->isFileContext() &&
10482 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCallc96cd7a2013-03-20 01:53:00 +000010483 F.erase();
Douglas Gregord9433522013-06-27 20:42:30 +000010484 FriendSawTagOutsideEnclosingNamespace = true;
10485 }
John McCallc96cd7a2013-03-20 01:53:00 +000010486 }
10487 F.done();
10488 }
Douglas Gregor61c6c442011-05-04 00:25:33 +000010489
John McCall68263142009-11-18 22:49:29 +000010490 // Note: there used to be some attempt at recovery here.
10491 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010492 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +000010493
David Blaikie4e4d0842012-03-11 07:00:24 +000010494 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +000010495 // FIXME: This makes sure that we ignore the contexts associated
10496 // with C structs, unions, and enums when looking for a matching
10497 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +000010498 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010499 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10500 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +000010501 }
Douglas Gregor069ea642010-09-16 23:58:57 +000010502 } else if (S->isFunctionPrototypeScope()) {
10503 // If this is an enum declaration in function prototype scope, set its
10504 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +000010505 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +000010506 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010507 }
10508
John McCall68263142009-11-18 22:49:29 +000010509 if (Previous.isSingleResult() &&
10510 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010511 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +000010512 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +000010513 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +000010514 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +000010515 }
10516
David Blaikie4e4d0842012-03-11 07:00:24 +000010517 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010518 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010519 // This is a declaration of or a reference to "std::bad_alloc".
10520 isStdBadAlloc = true;
10521
John McCall68263142009-11-18 22:49:29 +000010522 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010523 // std::bad_alloc has been implicitly declared (but made invisible to
10524 // name lookup). Fill in this implicit declaration as the previous
10525 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010526 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010527 }
10528 }
John McCall68263142009-11-18 22:49:29 +000010529
John McCall9c86b512010-03-25 21:28:06 +000010530 // If we didn't find a previous declaration, and this is a reference
10531 // (or friend reference), move to the correct scope. In C++, we
10532 // also need to do a redeclaration lookup there, just in case
10533 // there's a shadow friend decl.
10534 if (Name && Previous.empty() &&
10535 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10536 if (Invalid) goto CreateNewDecl;
10537 assert(SS.isEmpty());
10538
10539 if (TUK == TUK_Reference) {
10540 // C++ [basic.scope.pdecl]p5:
10541 // -- for an elaborated-type-specifier of the form
10542 //
10543 // class-key identifier
10544 //
10545 // if the elaborated-type-specifier is used in the
10546 // decl-specifier-seq or parameter-declaration-clause of a
10547 // function defined in namespace scope, the identifier is
10548 // declared as a class-name in the namespace that contains
10549 // the declaration; otherwise, except as a friend
10550 // declaration, the identifier is declared in the smallest
10551 // non-class, non-function-prototype scope that contains the
10552 // declaration.
10553 //
10554 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10555 // C structs and unions.
10556 //
10557 // It is an error in C++ to declare (rather than define) an enum
10558 // type, including via an elaborated type specifier. We'll
10559 // diagnose that later; for now, declare the enum in the same
10560 // scope as we would have picked for any other tag type.
10561 //
10562 // GNU C also supports this behavior as part of its incomplete
10563 // enum types extension, while GNU C++ does not.
10564 //
10565 // Find the context where we'll be declaring the tag.
10566 // FIXME: We would like to maintain the current DeclContext as the
10567 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +000010568 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +000010569 SearchDC = SearchDC->getParent();
10570
10571 // Find the scope where we'll be declaring the tag.
10572 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010573 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +000010574 S->isFunctionPrototypeScope()) ||
10575 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +000010576 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCall9c86b512010-03-25 21:28:06 +000010577 S = S->getParent();
10578 } else {
10579 assert(TUK == TUK_Friend);
10580 // C++ [namespace.memdef]p3:
10581 // If a friend declaration in a non-local class first declares a
10582 // class or function, the friend class or function is a member of
10583 // the innermost enclosing namespace.
10584 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +000010585 }
10586
John McCall0d6b1642010-04-23 18:46:30 +000010587 // In C++, we need to do a redeclaration lookup to properly
10588 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +000010589 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +000010590 Previous.setRedeclarationKind(ForRedeclaration);
10591 LookupQualifiedName(Previous, SearchDC);
10592 }
10593 }
10594
John McCall68263142009-11-18 22:49:29 +000010595 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +000010596 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +000010597
10598 // It's okay to have a tag decl in the same scope as a typedef
10599 // which hides a tag decl in the same scope. Finding this
10600 // insanity with a redeclaration lookup can only actually happen
10601 // in C++.
10602 //
10603 // This is also okay for elaborated-type-specifiers, which is
10604 // technically forbidden by the current standard but which is
10605 // okay according to the likely resolution of an open issue;
10606 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +000010607 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +000010608 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +000010609 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10610 TagDecl *Tag = TT->getDecl();
10611 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010612 Tag->getDeclContext()->getRedeclContext()
10613 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +000010614 PrevDecl = Tag;
10615 Previous.clear();
10616 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +000010617 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +000010618 }
10619 }
10620 }
10621 }
10622
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010623 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010624 // If this is a use of a previous tag, or if the tag is already declared
10625 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010626 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +000010627 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +000010628 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010629 // Make sure that this wasn't declared as an enum and now used as a
10630 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +000010631 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10632 TUK == TUK_Definition, KWLoc,
10633 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +000010634 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010635 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10636 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +000010637 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +000010638 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +000010639 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +000010640 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10641 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +000010642 else
10643 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +000010644 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +000010645
Mike Stump1eb44332009-09-09 15:08:12 +000010646 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +000010647 Kind = PrevTagDecl->getTagKind();
10648 else {
10649 // Recover by making this an anonymous redefinition.
10650 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010651 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +000010652 Invalid = true;
10653 }
10654 }
10655
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010656 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10657 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10658
Richard Smithbdad7a22012-01-10 01:33:14 +000010659 // If this is an elaborated-type-specifier for a scoped enumeration,
10660 // the 'class' keyword is not necessary and not permitted.
10661 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10662 if (ScopedEnum)
10663 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10664 << PrevEnum->isScoped()
10665 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10666 return PrevTagDecl;
10667 }
10668
Richard Smithf1c66b42012-03-14 23:13:10 +000010669 QualType EnumUnderlyingTy;
10670 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10671 EnumUnderlyingTy = TI->getType();
10672 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10673 EnumUnderlyingTy = QualType(T, 0);
10674
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010675 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +000010676 // returning the previous declaration, unless this is a definition,
10677 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +000010678 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10679 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +000010680 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010681 }
10682
David Majnemer2ec2b842013-06-11 03:51:23 +000010683 // C++11 [class.mem]p1:
David Majnemer0f9b8552013-06-11 06:19:45 +000010684 // A member shall not be declared twice in the member-specification,
David Majnemer2ec2b842013-06-11 03:51:23 +000010685 // except that a nested class or member class template can be declared
10686 // and then later defined.
10687 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10688 S->isDeclScope(PrevDecl)) {
10689 Diag(NameLoc, diag::ext_member_redeclared);
10690 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10691 }
10692
Douglas Gregora3a83512009-04-01 23:51:29 +000010693 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010694 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +000010695
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010696 // FIXME: In the future, return a variant or some other clue
10697 // for the consumer of this Decl to know it doesn't own it.
10698 // For our current ASTs this shouldn't be a problem, but will
10699 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +000010700 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010701 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +000010702 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010703
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010704 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +000010705 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +000010706 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010707 // If we're defining a specialization and the previous definition
10708 // is from an implicit instantiation, don't emit an error
10709 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +000010710 bool IsExplicitSpecializationAfterInstantiation = false;
10711 if (isExplicitSpecialization) {
10712 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10713 IsExplicitSpecializationAfterInstantiation =
10714 RD->getTemplateSpecializationKind() !=
10715 TSK_ExplicitSpecialization;
10716 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10717 IsExplicitSpecializationAfterInstantiation =
10718 ED->getTemplateSpecializationKind() !=
10719 TSK_ExplicitSpecialization;
10720 }
10721
10722 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +000010723 // A redeclaration in function prototype scope in C isn't
10724 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +000010725 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +000010726 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10727 else
10728 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010729 Diag(Def->getLocation(), diag::note_previous_definition);
10730 // If this is a redefinition, recover by making this
10731 // struct be anonymous, which will make any later
10732 // references get the previous definition.
10733 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010734 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010735 Invalid = true;
10736 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010737 } else {
10738 // If the type is currently being defined, complain
10739 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +000010740 const TagType *Tag
10741 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010742 if (Tag->isBeingDefined()) {
10743 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +000010744 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010745 diag::note_previous_definition);
10746 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010747 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010748 Invalid = true;
10749 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010750 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010751
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010752 // Okay, this is definition of a previously declared or referenced
10753 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010754 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010755 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010756 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +000010757 // have a definition. Just create a new decl.
10758
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010759 } else {
10760 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +000010761 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010762 // new decl/type. We set PrevDecl to NULL so that the entities
10763 // have distinct types.
John McCall68263142009-11-18 22:49:29 +000010764 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010765 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010766 // If we get here, we're going to create a new Decl. If PrevDecl
10767 // is non-NULL, it's a definition of the tag declared by
10768 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +000010769
10770
10771 // Otherwise, PrevDecl is not a tag, but was found with tag
10772 // lookup. This is only actually possible in C++, where a few
10773 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010774 } else {
John McCall0d6b1642010-04-23 18:46:30 +000010775 // Use a better diagnostic if an elaborated-type-specifier
10776 // found the wrong kind of type on the first
10777 // (non-redeclaration) lookup.
10778 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10779 !Previous.isForRedeclaration()) {
10780 unsigned Kind = 0;
10781 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010782 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10783 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010784 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10785 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10786 Invalid = true;
10787
10788 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +000010789 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10790 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +000010791 // do nothing
10792
10793 // Diagnose implicit declarations introduced by elaborated types.
10794 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10795 unsigned Kind = 0;
10796 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010797 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10798 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010799 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10800 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10801 Invalid = true;
10802
10803 // Otherwise it's a declaration. Call out a particularly common
10804 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +000010805 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10806 unsigned Kind = 0;
10807 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +000010808 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +000010809 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +000010810 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10811 Invalid = true;
10812
10813 // Otherwise, diagnose.
10814 } else {
10815 // The tag name clashes with something else in the target scope,
10816 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +000010817 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010818 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010819 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010820 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010821 }
John McCall0d6b1642010-04-23 18:46:30 +000010822
10823 // The existing declaration isn't relevant to us; we're in a
10824 // new scope, so clear out the previous declaration.
10825 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010826 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010827 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000010828
Chris Lattnercc98eac2008-12-17 07:13:27 +000010829CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +000010830
John McCall68263142009-11-18 22:49:29 +000010831 TagDecl *PrevDecl = 0;
10832 if (Previous.isSingleResult())
10833 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10834
Reid Spencer5f016e22007-07-11 17:01:13 +000010835 // If there is an identifier, use the location of the identifier as the
10836 // location of the decl, otherwise use the location of the struct/union
10837 // keyword.
10838 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000010839
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010840 // Otherwise, create a new declaration. If there is a previous
10841 // declaration of the same entity, the two will be linked via
10842 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +000010843 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +000010844
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010845 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010846 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010847 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10848 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010849 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010850 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010851 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +000010852 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010853 if (TUK != TUK_Definition && !Invalid) {
10854 TagDecl *Def;
Douglas Gregorabde2c72013-03-25 22:22:35 +000010855 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10856 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010857 // C++0x: 7.2p2: opaque-enum-declaration.
10858 // Conflicts are diagnosed above. Do nothing.
10859 }
10860 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010861 Diag(Loc, diag::ext_forward_ref_enum_def)
10862 << New;
10863 Diag(Def->getLocation(), diag::note_previous_definition);
10864 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010865 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010866 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010867 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010868 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010869 DiagID = diag::err_forward_ref_enum;
10870 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010871
10872 // If this is a forward-declared reference to an enumeration, make a
10873 // note of it; we won't actually be introducing the declaration into
10874 // the declaration context.
10875 if (TUK == TUK_Reference)
10876 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010877 }
Douglas Gregor80711a22009-03-06 18:34:03 +000010878 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010879
10880 if (EnumUnderlying) {
10881 EnumDecl *ED = cast<EnumDecl>(New);
10882 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10883 ED->setIntegerTypeSourceInfo(TI);
10884 else
10885 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10886 ED->setPromotionType(ED->getIntegerType());
10887 }
10888
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000010889 } else {
10890 // struct/union/class
10891
Reid Spencer5f016e22007-07-11 17:01:13 +000010892 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10893 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +000010894 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +000010895 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010896 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010897 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010898
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010899 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010900 StdBadAlloc = cast<CXXRecordDecl>(New);
10901 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010902 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010903 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000010904 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010905
John McCallb6217662010-03-15 10:12:16 +000010906 // Maybe add qualifier info.
10907 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010908 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +000010909 // If this is either a declaration or a definition, check the
10910 // nested-name-specifier against the current context. We don't do this
10911 // for explicit specializations, because they have similar checking
10912 // (with more specific diagnostics) in the call to
10913 // CheckMemberSpecialization, below.
10914 if (!isExplicitSpecialization &&
10915 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10916 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10917 Invalid = true;
10918
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000010919 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010920 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +000010921 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010922 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010923 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +000010924 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010925 }
10926 else
10927 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +000010928 }
10929
Daniel Dunbar9f21f892010-05-27 01:53:40 +000010930 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10931 // Add alignment attributes if necessary; these attributes are checked when
10932 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010933 //
10934 // It is important for implementing the correct semantics that this
10935 // happen here (in act on tag decl). The #pragma pack stack is
10936 // maintained as a result of parser callbacks which can occur at
10937 // many points during the parsing of a struct declaration (because
10938 // the #pragma tokens are effectively skipped over during the
10939 // parsing of the struct).
Eli Friedman2016c8c2012-08-08 21:08:34 +000010940 if (TUK == TUK_Definition) {
10941 AddAlignmentAttributesForRecord(RD);
10942 AddMsStructLayoutForRecord(RD);
10943 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010944 }
10945
Douglas Gregor2ccd89c2011-12-20 18:11:52 +000010946 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +000010947 if (isExplicitSpecialization)
10948 Diag(New->getLocation(), diag::err_module_private_specialization)
10949 << 2
10950 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +000010951 // __module_private__ does not apply to local classes. However, we only
10952 // diagnose this as an error when the declaration specifiers are
10953 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +000010954 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +000010955 New->setModulePrivate();
10956 }
10957
Douglas Gregorf6b11852009-10-08 15:14:33 +000010958 // If this is a specialization of a member class (of a class template),
10959 // check the specialization.
John McCall68263142009-11-18 22:49:29 +000010960 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +000010961 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +000010962
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010963 if (Invalid)
10964 New->setInvalidDecl();
10965
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010966 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010967 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010968
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010969 // If we're declaring or defining a tag in function prototype scope
10970 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +000010971 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +000010972 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
10973
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010974 // Set the lexical context. If the tag has a C++ scope specifier, the
10975 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +000010976 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010977
John McCall02cace72009-08-28 07:59:38 +000010978 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +000010979 // In Microsoft mode, a friend declaration also acts as a forward
10980 // declaration so we always pass true to setObjectOfFriendDecl to make
10981 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +000010982 if (TUK == TUK_Friend)
Richard Smith22050f22013-07-17 23:53:16 +000010983 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
10984 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +000010985
Anders Carlsson0cf88302009-03-26 01:19:02 +000010986 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +000010987 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +000010988 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +000010989
John McCall0f434ec2009-07-31 02:45:11 +000010990 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010991 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +000010992
Reid Spencer5f016e22007-07-11 17:01:13 +000010993 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +000010994 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +000010995 // We might be replacing an existing declaration in the lookup tables;
10996 // if so, borrow its access specifier.
10997 if (PrevDecl)
10998 New->setAccess(PrevDecl->getAccess());
10999
Sebastian Redl7a126a42010-08-31 00:36:30 +000011000 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011001 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +000011002 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +000011003 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11004 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +000011005 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000011006 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011007 PushOnScopeChains(New, S, !IsForwardReference);
11008 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011009 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011010
Douglas Gregor4920f1f2009-01-12 22:49:06 +000011011 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011012 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +000011013 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000011014
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011015 // If this is the C FILE type, notify the AST context.
11016 if (IdentifierInfo *II = New->getIdentifier())
11017 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000011018 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011019 II->isStr("FILE"))
11020 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +000011021
James Molloy16f1f712012-02-29 10:24:19 +000011022 // If we were in function prototype scope (and not in C++ mode), add this
11023 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +000011024 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +000011025 InFunctionDeclarator && Name)
11026 DeclsInPrototypeScope.push_back(New);
11027
Rafael Espindola98ae8342012-05-10 02:50:16 +000011028 if (PrevDecl)
11029 mergeDeclAttributes(New, PrevDecl);
11030
Rafael Espindola71adc5b2012-07-17 15:14:47 +000011031 // If there's a #pragma GCC visibility in scope, set the visibility of this
11032 // record.
11033 AddPushedVisibilityAttribute(New);
11034
Douglas Gregor402abb52009-05-28 23:31:59 +000011035 OwnedDecl = true;
Richard Smith37ec8d52012-12-05 11:34:06 +000011036 // In C++, don't return an invalid declaration. We can't recover well from
11037 // the cases where we make the type anonymous.
11038 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Reid Spencer5f016e22007-07-11 17:01:13 +000011039}
11040
John McCalld226f652010-08-21 09:40:31 +000011041void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011042 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011043 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +000011044
Douglas Gregor72de6672009-01-08 20:45:30 +000011045 // Enter the tag context.
11046 PushDeclContext(S, Tag);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000011047
11048 ActOnDocumentableDecl(TagD);
Rafael Espindola5e065292012-07-12 04:47:34 +000011049
11050 // If there's a #pragma GCC visibility in scope, set the visibility of this
11051 // record.
11052 AddPushedVisibilityAttribute(Tag);
John McCallf9368152009-12-20 07:58:13 +000011053}
Douglas Gregor72de6672009-01-08 20:45:30 +000011054
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011055Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011056 assert(isa<ObjCContainerDecl>(IDecl) &&
11057 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11058 DeclContext *OCD = cast<DeclContext>(IDecl);
11059 assert(getContainingDC(OCD) == CurContext &&
11060 "The next DeclContext should be lexically contained in the current one.");
11061 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011062 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011063}
11064
John McCalld226f652010-08-21 09:40:31 +000011065void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011066 SourceLocation FinalLoc,
David Majnemer7121bdb2013-10-18 00:33:31 +000011067 bool IsFinalSpelledSealed,
John McCallf9368152009-12-20 07:58:13 +000011068 SourceLocation LBraceLoc) {
11069 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011070 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +000011071
John McCallf9368152009-12-20 07:58:13 +000011072 FieldCollector->StartClass();
11073
11074 if (!Record->getIdentifier())
11075 return;
11076
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011077 if (FinalLoc.isValid())
David Majnemer7121bdb2013-10-18 00:33:31 +000011078 Record->addAttr(new (Context)
11079 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11080
John McCallf9368152009-12-20 07:58:13 +000011081 // C++ [class]p2:
11082 // [...] The class-name is also inserted into the scope of the
11083 // class itself; this is known as the injected-class-name. For
11084 // purposes of access checking, the injected-class-name is treated
11085 // as if it were a public member name.
11086 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000011087 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11088 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +000011089 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +000011090 /*PrevDecl=*/0,
11091 /*DelayTypeCreation=*/true);
11092 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +000011093 InjectedClassName->setImplicit();
11094 InjectedClassName->setAccess(AS_public);
11095 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11096 InjectedClassName->setDescribedClassTemplate(Template);
11097 PushOnScopeChains(InjectedClassName, S);
11098 assert(InjectedClassName->isInjectedClassName() &&
11099 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +000011100}
11101
John McCalld226f652010-08-21 09:40:31 +000011102void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011103 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011104 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011105 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011106 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +000011107
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011108 // Make sure we "complete" the definition even it is invalid.
11109 if (Tag->isBeingDefined()) {
11110 assert(Tag->isInvalidDecl() && "We should already have completed it");
11111 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11112 RD->completeDefinition();
11113 }
11114
Douglas Gregor72de6672009-01-08 20:45:30 +000011115 if (isa<CXXRecordDecl>(Tag))
11116 FieldCollector->FinishClass();
11117
11118 // Exit this scope of this tag's definition.
11119 PopDeclContext();
Argyrios Kyrtzidis3d207e72013-01-29 18:00:54 +000011120
11121 if (getCurLexicalContext()->isObjCContainer() &&
11122 Tag->getDeclContext()->isFileContext())
11123 Tag->setTopLevelDeclInObjCContainer();
11124
Douglas Gregor72de6672009-01-08 20:45:30 +000011125 // Notify the consumer that we've defined a tag.
Serge Pavlov439b7012013-07-02 17:31:56 +000011126 if (!Tag->isInvalidDecl())
11127 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor72de6672009-01-08 20:45:30 +000011128}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +000011129
Fariborz Jahanian10af8792011-08-29 17:33:12 +000011130void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011131 // Exit this scope of this interface definition.
11132 PopDeclContext();
11133}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011134
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011135void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +000011136 assert(DC == CurContext && "Mismatch of container contexts");
11137 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011138 ActOnObjCContainerFinishDefinition();
11139}
11140
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011141void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11142 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011143 OriginalLexicalContext = 0;
11144}
11145
John McCalld226f652010-08-21 09:40:31 +000011146void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +000011147 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011148 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +000011149 Tag->setInvalidDecl();
11150
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011151 // Make sure we "complete" the definition even it is invalid.
11152 if (Tag->isBeingDefined()) {
11153 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11154 RD->completeDefinition();
11155 }
11156
John McCalla8cab012010-03-17 19:25:57 +000011157 // We're undoing ActOnTagStartDefinition here, not
11158 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11159 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +000011160
11161 PopDeclContext();
11162}
11163
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011164// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +000011165ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11166 IdentifierInfo *FieldName,
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011167 QualType FieldTy, bool IsMsStruct,
11168 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +000011169 // Default to true; that shouldn't confuse checks for emptiness
11170 if (ZeroWidth)
11171 *ZeroWidth = true;
11172
Chris Lattner24793662009-03-05 22:45:59 +000011173 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +000011174 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000011175 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +000011176 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +000011177 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +000011178 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011179 if (FieldName)
11180 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11181 << FieldName << FieldTy << BitWidth->getSourceRange();
11182 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11183 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +000011184 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11185 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +000011186 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011187
11188 // If the bit-width is type- or value-dependent, don't try to check
11189 // it now.
11190 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +000011191 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011192
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011193 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +000011194 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11195 if (ICE.isInvalid())
11196 return ICE;
11197 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011198
Eli Friedman1d954f62009-08-15 21:55:26 +000011199 if (Value != 0 && ZeroWidth)
11200 *ZeroWidth = false;
11201
Chris Lattnercd087072008-12-12 04:56:04 +000011202 // Zero-width bitfield is ok for anonymous field.
11203 if (Value == 0 && FieldName)
11204 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +000011205
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011206 if (Value.isSigned() && Value.isNegative()) {
11207 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +000011208 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011209 << FieldName << Value.toString(10);
11210 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11211 << Value.toString(10);
11212 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011213
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011214 if (!FieldTy->isDependentType()) {
11215 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011216 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011217 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlsson72468ec2010-04-16 15:16:32 +000011218 if (FieldName)
11219 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11220 << FieldName << (unsigned)Value.getZExtValue()
11221 << (unsigned)TypeSize;
11222
11223 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11224 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11225 }
11226
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011227 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +000011228 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11229 << FieldName << (unsigned)Value.getZExtValue()
11230 << (unsigned)TypeSize;
11231 else
11232 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11233 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011234 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011235 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011236
Richard Smith282e7e62012-02-04 09:53:13 +000011237 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011238}
11239
Richard Smith7a614d82011-06-11 17:19:42 +000011240/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +000011241/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +000011242Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011243 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +000011244 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +000011245 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smithca523302012-06-10 03:12:00 +000011246 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCalld226f652010-08-21 09:40:31 +000011247 return Res;
Chris Lattner24793662009-03-05 22:45:59 +000011248}
11249
11250/// HandleField - Analyze a field of a C struct or a C++ data member.
11251///
11252FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11253 SourceLocation DeclStart,
Richard Smithca523302012-06-10 03:12:00 +000011254 Declarator &D, Expr *BitWidth,
11255 InClassInitStyle InitStyle,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011256 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011257 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +000011258 SourceLocation Loc = DeclStart;
11259 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011260
John McCallbf1a0282010-06-04 23:28:52 +000011261 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11262 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +000011263 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011264 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +000011265
Douglas Gregore1862692010-12-15 23:18:36 +000011266 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11267 UPPC_DataMemberType)) {
11268 D.setInvalidType();
11269 T = Context.IntTy;
11270 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11271 }
11272 }
11273
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011274 // TR 18037 does not allow fields to be declared with address spaces.
11275 if (T.getQualifiers().hasAddressSpace()) {
11276 Diag(Loc, diag::err_field_with_address_space);
11277 D.setInvalidType();
11278 }
11279
Guy Benyeie6b9d802013-01-20 12:31:11 +000011280 // OpenCL 1.2 spec, s6.9 r:
11281 // The event type cannot be used to declare a structure or union field.
11282 if (LangOpts.OpenCL && T->isEventT()) {
11283 Diag(Loc, diag::err_event_t_struct_field);
11284 D.setInvalidType();
11285 }
11286
Richard Smithc7f81162013-03-18 22:52:47 +000011287 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +000011288
Richard Smithec642442013-04-12 22:46:28 +000011289 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11290 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11291 diag::err_invalid_thread)
11292 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011293
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011294 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +000011295 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011296 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11297 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +000011298 switch (Previous.getResultKind()) {
11299 case LookupResult::Found:
11300 case LookupResult::FoundUnresolvedValue:
11301 PrevDecl = Previous.getAsSingle<NamedDecl>();
11302 break;
11303
11304 case LookupResult::FoundOverloaded:
11305 PrevDecl = Previous.getRepresentativeDecl();
11306 break;
11307
11308 case LookupResult::NotFound:
11309 case LookupResult::NotFoundInCurrentInstantiation:
11310 case LookupResult::Ambiguous:
11311 break;
11312 }
11313 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +000011314
11315 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11316 // Maybe we will complain about the shadowed template parameter.
11317 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11318 // Just pretend that we didn't see the previous declaration.
11319 PrevDecl = 0;
11320 }
11321
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011322 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11323 PrevDecl = 0;
11324
Steve Naroffea218b82009-07-14 14:58:18 +000011325 bool Mutable
11326 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +000011327 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +000011328 FieldDecl *NewFD
Richard Smithca523302012-06-10 03:12:00 +000011329 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith7a614d82011-06-11 17:19:42 +000011330 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +000011331
11332 if (NewFD->isInvalidDecl())
11333 Record->setInvalidDecl();
11334
Douglas Gregor591dc842011-09-12 16:11:24 +000011335 if (D.getDeclSpec().isModulePrivateSpecified())
11336 NewFD->setModulePrivate();
11337
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011338 if (NewFD->isInvalidDecl() && PrevDecl) {
11339 // Don't introduce NewFD into scope; there's already something
11340 // with the same name in the same scope.
11341 } else if (II) {
11342 PushOnScopeChains(NewFD, S);
11343 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011344 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011345
11346 return NewFD;
11347}
11348
11349/// \brief Build a new FieldDecl and check its well-formedness.
11350///
11351/// This routine builds a new FieldDecl given the fields name, type,
11352/// record, etc. \p PrevDecl should refer to any previous declaration
11353/// with the same name and in the same scope as the field to be
11354/// created.
11355///
11356/// \returns a new FieldDecl.
11357///
Mike Stump1eb44332009-09-09 15:08:12 +000011358/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +000011359FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000011360 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011361 RecordDecl *Record, SourceLocation Loc,
Richard Smithca523302012-06-10 03:12:00 +000011362 bool Mutable, Expr *BitWidth,
11363 InClassInitStyle InitStyle,
Steve Naroffea218b82009-07-14 14:58:18 +000011364 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011365 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011366 Declarator *D) {
11367 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +000011368 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +000011369 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +000011370
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011371 // If we receive a broken type, recover by assuming 'int' and
11372 // marking this declaration as invalid.
11373 if (T.isNull()) {
11374 InvalidDecl = true;
11375 T = Context.IntTy;
11376 }
11377
Eli Friedman721e77d2009-12-07 00:22:08 +000011378 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011379 if (!EltTy->isDependentType()) {
11380 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11381 // Fields of incomplete type force their record to be invalid.
11382 Record->setInvalidDecl();
11383 InvalidDecl = true;
11384 } else {
11385 NamedDecl *Def;
11386 EltTy->isIncompleteType(&Def);
11387 if (Def && Def->isInvalidDecl()) {
11388 Record->setInvalidDecl();
11389 InvalidDecl = true;
11390 }
11391 }
John McCall2d7d2d92010-08-16 23:42:35 +000011392 }
Eli Friedman721e77d2009-12-07 00:22:08 +000011393
Joey Gouly617bb312013-01-17 17:35:00 +000011394 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11395 if (BitWidth && getLangOpts().OpenCL) {
11396 Diag(Loc, diag::err_opencl_bitfields);
11397 InvalidDecl = true;
11398 }
11399
Reid Spencer5f016e22007-07-11 17:01:13 +000011400 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11401 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +000011402 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011403 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +000011404 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011405
11406 TypeSourceInfo *FixedTInfo =
11407 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11408 SizeIsNegative,
11409 Oversized);
11410 if (FixedTInfo) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011411 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011412 TInfo = FixedTInfo;
11413 T = FixedTInfo->getType();
Eli Friedman1ca48132009-02-21 00:44:51 +000011414 } else {
11415 if (SizeIsNegative)
11416 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +000011417 else if (Oversized.getBoolValue())
11418 Diag(Loc, diag::err_array_too_large)
11419 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +000011420 else
11421 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +000011422 InvalidDecl = true;
11423 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011424 }
Mike Stump1eb44332009-09-09 15:08:12 +000011425
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011426 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +000011427 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11428 diag::err_abstract_type_in_decl,
11429 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011430 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +000011431
Eli Friedman1d954f62009-08-15 21:55:26 +000011432 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011433 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +000011434 if (!InvalidDecl && BitWidth) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011435 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11436 &ZeroWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011437 if (!BitWidth) {
11438 InvalidDecl = true;
11439 BitWidth = 0;
11440 ZeroWidth = false;
11441 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011442 }
Mike Stump1eb44332009-09-09 15:08:12 +000011443
John McCall4bde1e12010-06-04 08:34:12 +000011444 // Check that 'mutable' is consistent with the type of the declaration.
11445 if (!InvalidDecl && Mutable) {
11446 unsigned DiagID = 0;
11447 if (T->isReferenceType())
11448 DiagID = diag::err_mutable_reference;
11449 else if (T.isConstQualified())
11450 DiagID = diag::err_mutable_const;
11451
11452 if (DiagID) {
11453 SourceLocation ErrLoc = Loc;
11454 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11455 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11456 Diag(ErrLoc, DiagID);
11457 Mutable = false;
11458 InvalidDecl = true;
11459 }
11460 }
11461
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011462 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +000011463 BitWidth, Mutable, InitStyle);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011464 if (InvalidDecl)
11465 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +000011466
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011467 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11468 Diag(Loc, diag::err_duplicate_member) << II;
11469 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11470 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +000011471 }
11472
David Blaikie4e4d0842012-03-11 07:00:24 +000011473 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +000011474 if (Record->isUnion()) {
11475 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11476 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11477 if (RDecl->getDefinition()) {
11478 // C++ [class.union]p1: An object of a class with a non-trivial
11479 // constructor, a non-trivial copy constructor, a non-trivial
11480 // destructor, or a non-trivial copy assignment operator
11481 // cannot be a member of a union, nor can an array of such
11482 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +000011483 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +000011484 NewFD->setInvalidDecl();
11485 }
11486 }
11487
11488 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballman76eed422013-05-30 16:20:00 +000011489 // the program is ill-formed, except when compiling with MSVC extensions
11490 // enabled.
Anders Carlssondfdfc582010-11-07 19:13:55 +000011491 if (EltTy->isReferenceType()) {
Aaron Ballman76eed422013-05-30 16:20:00 +000011492 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11493 diag::ext_union_member_of_reference_type :
11494 diag::err_union_member_of_reference_type)
Anders Carlssondfdfc582010-11-07 19:13:55 +000011495 << NewFD->getDeclName() << EltTy;
Aaron Ballman76eed422013-05-30 16:20:00 +000011496 if (!getLangOpts().MicrosoftExt)
11497 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +000011498 }
11499 }
11500 }
11501
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011502 // FIXME: We need to pass in the attributes given an AST
11503 // representation, not a parser representation.
Richard Smithbe507b62013-02-01 08:12:08 +000011504 if (D) {
Douglas Gregor92eb7d82013-05-02 23:25:32 +000011505 // FIXME: The current scope is almost... but not entirely... correct here.
11506 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011507
Richard Smithbe507b62013-02-01 08:12:08 +000011508 if (NewFD->hasAttrs())
11509 CheckAlignasUnderalignment(NewFD);
11510 }
11511
John McCallf85e1932011-06-15 23:02:42 +000011512 // In auto-retain/release, infer strong retension for fields of
11513 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011514 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +000011515 NewFD->setInvalidDecl();
11516
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +000011517 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +000011518 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +000011519
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011520 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +000011521 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +000011522}
11523
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011524bool Sema::CheckNontrivialField(FieldDecl *FD) {
11525 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +000011526 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011527
Nick Lewyckydccd04d2013-06-25 23:22:23 +000011528 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11529 return false;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011530
11531 QualType EltTy = Context.getBaseElementType(FD->getType());
11532 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smithac713512012-12-08 02:53:02 +000011533 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011534 if (RDecl->getDefinition()) {
11535 // We check for copy constructors before constructors
11536 // because otherwise we'll never get complaints about
11537 // copy constructors.
11538
11539 CXXSpecialMember member = CXXInvalid;
Richard Smith426391c2012-11-16 00:53:38 +000011540 // We're required to check for any non-trivial constructors. Since the
11541 // implicit default constructor is suppressed if there are any
11542 // user-declared constructors, we just need to check that there is a
11543 // trivial default constructor and a trivial copy constructor. (We don't
11544 // worry about move constructors here, since this is a C++98 check.)
11545 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011546 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +000011547 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +000011548 member = CXXDefaultConstructor;
Richard Smith426391c2012-11-16 00:53:38 +000011549 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011550 member = CXXCopyAssignment;
Richard Smith426391c2012-11-16 00:53:38 +000011551 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011552 member = CXXDestructor;
11553
11554 if (member != CXXInvalid) {
Richard Smith80ad52f2013-01-02 11:42:31 +000011555 if (!getLangOpts().CPlusPlus11 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011556 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +000011557 // Objective-C++ ARC: it is an error to have a non-trivial field of
11558 // a union. However, system headers in Objective-C programs
11559 // occasionally have Objective-C lifetime objects within unions,
11560 // and rather than cause the program to fail, we make those
11561 // members unavailable.
11562 SourceLocation Loc = FD->getLocation();
11563 if (getSourceManager().isInSystemHeader(Loc)) {
11564 if (!FD->hasAttr<UnavailableAttr>())
11565 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011566 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011567 return false;
11568 }
11569 }
Richard Smithe7d7c392011-10-19 20:41:51 +000011570
Richard Smith80ad52f2013-01-02 11:42:31 +000011571 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithe7d7c392011-10-19 20:41:51 +000011572 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11573 diag::err_illegal_union_or_anon_struct_member)
11574 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smithac713512012-12-08 02:53:02 +000011575 DiagnoseNontrivial(RDecl, member);
Richard Smith80ad52f2013-01-02 11:42:31 +000011576 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011577 }
11578 }
11579 }
Richard Smithac713512012-12-08 02:53:02 +000011580
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011581 return false;
11582}
11583
Mike Stump1eb44332009-09-09 15:08:12 +000011584/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011585/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011586static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011587TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +000011588 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +000011589 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +000011590 case tok::objc_private: return ObjCIvarDecl::Private;
11591 case tok::objc_public: return ObjCIvarDecl::Public;
11592 case tok::objc_protected: return ObjCIvarDecl::Protected;
11593 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +000011594 }
11595}
11596
Mike Stump1eb44332009-09-09 15:08:12 +000011597/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +000011598/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +000011599Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +000011600 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011601 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +000011602 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +000011603
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011604 IdentifierInfo *II = D.getIdentifier();
11605 Expr *BitWidth = (Expr*)BitfieldWidth;
11606 SourceLocation Loc = DeclStart;
11607 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011608
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011609 // FIXME: Unnamed fields can be handled in various different ways, for
11610 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +000011611
John McCallbf1a0282010-06-04 23:28:52 +000011612 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11613 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000011614
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011615 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +000011616 // 6.7.2.1p3, 6.7.2.1p4
Warren Huntb2969b12013-10-11 20:19:00 +000011617 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011618 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +000011619 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011620 } else {
11621 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +000011622
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011623 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +000011624
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011625 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011626 if (T->isReferenceType()) {
11627 Diag(Loc, diag::err_ivar_reference_type);
11628 D.setInvalidType();
11629 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011630 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11631 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011632 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +000011633 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011634 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011635 }
Mike Stump1eb44332009-09-09 15:08:12 +000011636
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011637 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +000011638 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011639 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11640 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011641 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011642 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +000011643 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11644 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +000011645 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +000011646 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011647 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011648 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011649 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +000011650 EnclosingContext = IMPDecl->getClassInterface();
11651 assert(EnclosingContext && "Implementation has no class interface!");
11652 }
11653 else
11654 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011655 } else {
11656 if (ObjCCategoryDecl *CDecl =
11657 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011658 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011659 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +000011660 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011661 }
11662 }
Daniel Dunbara19331f2010-04-02 18:29:09 +000011663 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011664 }
Mike Stump1eb44332009-09-09 15:08:12 +000011665
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011666 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011667 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11668 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +000011669 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +000011670
Douglas Gregor72de6672009-01-08 20:45:30 +000011671 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000011672 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +000011673 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011674 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +000011675 && !isa<TagDecl>(PrevDecl)) {
11676 Diag(Loc, diag::err_duplicate_member) << II;
11677 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11678 NewID->setInvalidDecl();
11679 }
11680 }
11681
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011682 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011683 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +000011684
Chris Lattnereaaebc72009-04-25 08:06:05 +000011685 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011686 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011687
John McCallf85e1932011-06-15 23:02:42 +000011688 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011689 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +000011690 NewID->setInvalidDecl();
11691
Douglas Gregor591dc842011-09-12 16:11:24 +000011692 if (D.getDeclSpec().isModulePrivateSpecified())
11693 NewID->setModulePrivate();
11694
Douglas Gregor72de6672009-01-08 20:45:30 +000011695 if (II) {
11696 // FIXME: When interfaces are DeclContexts, we'll need to add
11697 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +000011698 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +000011699 IdResolver.AddDecl(NewID);
11700 }
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011701
John McCall260611a2012-06-20 06:18:46 +000011702 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011703 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniandc3eb6a2012-05-15 17:43:16 +000011704 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011705
John McCalld226f652010-08-21 09:40:31 +000011706 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011707}
11708
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011709/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosed4582b82013-04-03 01:39:23 +000011710/// class and class extensions. For every class \@interface and class
11711/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011712/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011713void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011714 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall260611a2012-06-20 06:18:46 +000011715 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011716 return;
11717
11718 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11719 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11720
Richard Smitha6b8b2c2011-10-10 18:28:20 +000011721 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011722 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011723 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011724 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011725 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011726 if (!CD->IsClassExtension())
11727 return;
11728 }
11729 // No need to add this to end of @implementation.
11730 else
11731 return;
11732 }
11733 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011734 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11735 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011736
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011737 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011738 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011739 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011740 Context.getTrivialTypeSourceInfo(Context.CharTy,
11741 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011742 ObjCIvarDecl::Private, BW,
11743 true);
11744 AllIvarDecls.push_back(Ivar);
11745}
11746
Robert Wilhelm834c0582013-08-09 18:02:13 +000011747void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11748 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11749 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +000011750 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +000011751
Eric Christopher6dba4a12012-07-19 22:22:51 +000011752 // If this is an Objective-C @implementation or category and we have
11753 // new fields here we should reset the layout of the interface since
11754 // it will now change.
11755 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11756 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11757 switch (DC->getKind()) {
11758 default: break;
11759 case Decl::ObjCCategory:
11760 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11761 break;
11762 case Decl::ObjCImplementation:
11763 Context.
11764 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11765 break;
11766 }
11767 }
11768
Eli Friedman11e70d72012-02-07 05:00:47 +000011769 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11770
11771 // Start counting up the number of named members; make sure to include
11772 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +000011773 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +000011774 if (Record) {
11775 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11776 e = Record->decls_end(); i != e; i++) {
11777 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11778 if (IFD->getDeclName())
11779 ++NumNamedMembers;
11780 }
11781 }
11782
11783 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011784 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011785
John McCallf85e1932011-06-15 23:02:42 +000011786 bool ARCErrReported = false;
Robert Wilhelm834c0582013-08-09 18:02:13 +000011787 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie77b6de02011-09-22 02:58:26 +000011788 i != end; ++i) {
11789 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +000011790
Reid Spencer5f016e22007-07-11 17:01:13 +000011791 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +000011792 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011793
Douglas Gregor72de6672009-01-08 20:45:30 +000011794 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011795 // Remember all fields written by the user.
11796 RecFields.push_back(FD);
11797 }
Mike Stump1eb44332009-09-09 15:08:12 +000011798
Chris Lattner24793662009-03-05 22:45:59 +000011799 // If the field is already invalid for some reason, don't emit more
11800 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +000011801 if (FD->isInvalidDecl()) {
11802 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +000011803 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +000011804 }
Mike Stump1eb44332009-09-09 15:08:12 +000011805
Douglas Gregore7450f52009-03-24 19:52:54 +000011806 // C99 6.7.2.1p2:
11807 // A structure or union shall not contain a member with
11808 // incomplete or function type (hence, a structure shall not
11809 // contain an instance of itself, but may contain a pointer to
11810 // an instance of itself), except that the last member of a
11811 // structure with more than one named member may have incomplete
11812 // array type; such a structure (and any union containing,
11813 // possibly recursively, a member that is such a structure)
11814 // shall not be a member of a structure or an element of an
11815 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +000011816 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011817 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011818 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011819 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011820 FD->setInvalidDecl();
11821 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011822 continue;
Francois Pichet09246182010-09-15 00:14:08 +000011823 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +000011824 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +000011825 ((getLangOpts().MicrosoftExt ||
11826 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +000011827 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011828 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011829 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +000011830 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +000011831 // as the sole element of a struct/class.
David Majnemer633c0c22013-11-02 10:38:05 +000011832 unsigned DiagID = 0;
11833 if (Record->isUnion())
11834 DiagID = getLangOpts().MicrosoftExt
11835 ? diag::ext_flexible_array_union_ms
11836 : getLangOpts().CPlusPlus
11837 ? diag::ext_flexible_array_union_gnu
11838 : diag::err_flexible_array_union;
11839 else if (Fields.size() == 1)
11840 DiagID = getLangOpts().MicrosoftExt
11841 ? diag::ext_flexible_array_empty_aggregate_ms
11842 : getLangOpts().CPlusPlus
11843 ? diag::ext_flexible_array_empty_aggregate_gnu
11844 : NumNamedMembers < 1
11845 ? diag::err_flexible_array_empty_aggregate
11846 : 0;
11847
11848 if (DiagID)
11849 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11850 << Record->getTagKind();
David Majnemer3a665572013-11-02 11:19:13 +000011851 // While the layout of types that contain virtual bases is not specified
11852 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11853 // virtual bases after the derived members. This would make a flexible
11854 // array member declared at the end of an object not adjacent to the end
11855 // of the type.
11856 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11857 if (RD->getNumVBases() != 0)
11858 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11859 << FD->getDeclName() << Record->getTagKind();
David Majnemer633c0c22013-11-02 10:38:05 +000011860 if (!getLangOpts().C99)
11861 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11862 << FD->getDeclName() << Record->getTagKind();
11863
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011864 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +000011865 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011866 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +000011867 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011868 FD->setInvalidDecl();
11869 EnclosingDecl->setInvalidDecl();
11870 continue;
11871 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011872 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +000011873 if (Record)
11874 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +000011875 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +000011876 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +000011877 diag::err_field_incomplete)) {
11878 // Incomplete type
11879 FD->setInvalidDecl();
11880 EnclosingDecl->setInvalidDecl();
11881 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +000011882 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011883 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11884 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000011885 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011886 Record->setHasFlexibleArrayMember(true);
11887 } else {
11888 // If this is a struct/class and this is not the last element, reject
11889 // it. Note that GCC supports variable sized arrays in the middle of
11890 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +000011891 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +000011892 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +000011893 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +000011894 else {
11895 // We support flexible arrays at the end of structs in
11896 // other structs as an extension.
11897 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11898 << FD->getDeclName();
11899 if (Record)
11900 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011901 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011902 }
11903 }
Fariborz Jahanian7f90b532012-08-16 22:38:41 +000011904 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11905 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11906 diag::err_abstract_type_in_decl,
11907 AbstractIvarType)) {
11908 // Ivars can not have abstract class types
11909 FD->setInvalidDecl();
11910 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000011911 if (Record && FDTTy->getDecl()->hasObjectMember())
11912 Record->setHasObjectMember(true);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011913 if (Record && FDTTy->getDecl()->hasVolatileMember())
11914 Record->setHasVolatileMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +000011915 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011916 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +000011917 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11918 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11919 QualType T = Context.getObjCObjectPointerType(FD->getType());
11920 FD->setType(T);
Douglas Gregor4581d452013-01-28 19:08:09 +000011921 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11922 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11923 // It's an error in ARC if a field has lifetime.
11924 // We don't want to report this in a system header, though,
11925 // so we just make the field unavailable.
11926 // FIXME: that's really not sufficient; we need to make the type
11927 // itself invalid to, say, initialize or copy.
11928 QualType T = FD->getType();
11929 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11930 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11931 SourceLocation loc = FD->getLocation();
11932 if (getSourceManager().isInSystemHeader(loc)) {
11933 if (!FD->hasAttr<UnavailableAttr>()) {
11934 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11935 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011936 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011937 } else {
11938 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregorbde67cf2013-01-28 20:13:44 +000011939 << T->isBlockPointerType() << Record->getTagKind();
John McCallf85e1932011-06-15 23:02:42 +000011940 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011941 ARCErrReported = true;
John McCallf85e1932011-06-15 23:02:42 +000011942 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011943 } else if (getLangOpts().ObjC1 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011944 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +000011945 Record && !Record->hasObjectMember()) {
Douglas Gregor4581d452013-01-28 19:08:09 +000011946 if (FD->getType()->isObjCObjectPointerType() ||
11947 FD->getType().isObjCGCStrong())
11948 Record->setHasObjectMember(true);
11949 else if (Context.getAsArrayType(FD->getType())) {
11950 QualType BaseType = Context.getBaseElementType(FD->getType());
11951 if (BaseType->isRecordType() &&
11952 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCallf85e1932011-06-15 23:02:42 +000011953 Record->setHasObjectMember(true);
Douglas Gregor4581d452013-01-28 19:08:09 +000011954 else if (BaseType->isObjCObjectPointerType() ||
11955 BaseType.isObjCGCStrong())
11956 Record->setHasObjectMember(true);
John McCallf85e1932011-06-15 23:02:42 +000011957 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +000011958 }
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011959 if (Record && FD->getType().isVolatileQualified())
11960 Record->setHasVolatileMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011961 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +000011962 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +000011963 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +000011964 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000011965
Reid Spencer5f016e22007-07-11 17:01:13 +000011966 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +000011967 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011968 bool Completed = false;
11969 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
11970 if (!CXXRecord->isInvalidDecl()) {
11971 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011972 for (CXXRecordDecl::conversion_iterator
11973 I = CXXRecord->conversion_begin(),
11974 E = CXXRecord->conversion_end(); I != E; ++I)
11975 I.setAccess((*I)->getAccess());
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011976
11977 if (!CXXRecord->isDependentType()) {
Peter Collingbournef51cfb82013-05-20 14:12:25 +000011978 if (CXXRecord->hasUserDeclaredDestructor()) {
11979 // Adjust user-defined destructor exception spec.
11980 if (getLangOpts().CPlusPlus11)
11981 AdjustDestructorExceptionSpec(CXXRecord,
11982 CXXRecord->getDestructor());
11983
11984 // The Microsoft ABI requires that we perform the destructor body
11985 // checks (i.e. operator delete() lookup) at every declaration, as
11986 // any translation unit may need to emit a deleting destructor.
11987 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11988 CheckDestructor(CXXRecord->getDestructor());
11989 }
Sebastian Redl0ee33912011-05-19 05:13:44 +000011990
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011991 // Add any implicitly-declared members to this class.
11992 AddImplicitlyDeclaredMembersToClass(CXXRecord);
11993
11994 // If we have virtual base classes, we may end up finding multiple
11995 // final overriders for a given virtual function. Check for this
11996 // problem now.
11997 if (CXXRecord->getNumVBases()) {
11998 CXXFinalOverriderMap FinalOverriders;
11999 CXXRecord->getFinalOverriders(FinalOverriders);
12000
12001 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12002 MEnd = FinalOverriders.end();
12003 M != MEnd; ++M) {
12004 for (OverridingMethods::iterator SO = M->second.begin(),
12005 SOEnd = M->second.end();
12006 SO != SOEnd; ++SO) {
12007 assert(SO->second.size() > 0 &&
12008 "Virtual function without overridding functions?");
12009 if (SO->second.size() == 1)
12010 continue;
12011
12012 // C++ [class.virtual]p2:
12013 // In a derived class, if a virtual member function of a base
12014 // class subobject has more than one final overrider the
12015 // program is ill-formed.
12016 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divacky31ba6132012-09-06 15:59:27 +000012017 << (const NamedDecl *)M->first << Record;
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012018 Diag(M->first->getLocation(),
12019 diag::note_overridden_virtual_function);
12020 for (OverridingMethods::overriding_iterator
12021 OM = SO->second.begin(),
12022 OMEnd = SO->second.end();
12023 OM != OMEnd; ++OM)
12024 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divacky31ba6132012-09-06 15:59:27 +000012025 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012026
12027 Record->setInvalidDecl();
12028 }
12029 }
12030 CXXRecord->completeDefinition(&FinalOverriders);
12031 Completed = true;
12032 }
12033 }
12034 }
12035 }
12036
12037 if (!Completed)
12038 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +000012039
Richard Smithbe507b62013-02-01 08:12:08 +000012040 if (Record->hasAttrs())
12041 CheckAlignasUnderalignment(Record);
Serge Pavlov122e6012013-06-08 13:29:58 +000012042
12043 // Check if the structure/union declaration is a language extension.
12044 if (!getLangOpts().CPlusPlus) {
12045 bool ZeroSize = true;
Serge Pavlov0dcea352013-06-17 17:18:51 +000012046 bool IsEmpty = true;
12047 unsigned NonBitFields = 0;
Serge Pavlov122e6012013-06-08 13:29:58 +000012048 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlov0dcea352013-06-17 17:18:51 +000012049 E = Record->field_end();
12050 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12051 IsEmpty = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012052 if (I->isUnnamedBitfield()) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012053 if (I->getBitWidthValue(Context) > 0)
12054 ZeroSize = false;
12055 } else {
Serge Pavlov0dcea352013-06-17 17:18:51 +000012056 ++NonBitFields;
12057 QualType FieldType = I->getType();
12058 if (FieldType->isIncompleteType() ||
12059 !Context.getTypeSizeInChars(FieldType).isZero())
12060 ZeroSize = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012061 }
12062 }
12063
12064 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
12065 // C++.
Serge Pavlov0dcea352013-06-17 17:18:51 +000012066 if (ZeroSize)
12067 Diag(RecLoc, diag::warn_zero_size_struct_union_compat) << IsEmpty
12068 << Record->isUnion() << (NonBitFields > 1);
Serge Pavlov122e6012013-06-08 13:29:58 +000012069
12070 // Structs without named members are extension in C (C99 6.7.2.1p7), but
12071 // are accepted by GCC.
Serge Pavlov0dcea352013-06-17 17:18:51 +000012072 if (NonBitFields == 0) {
12073 if (IsEmpty)
Serge Pavlov122e6012013-06-08 13:29:58 +000012074 Diag(RecLoc, diag::ext_empty_struct_union) << Record->isUnion();
12075 else
12076 Diag(RecLoc, diag::ext_no_named_members_in_struct_union) << Record->isUnion();
12077 }
12078 }
Chris Lattnere1e79852008-02-06 00:51:33 +000012079 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +000012080 ObjCIvarDecl **ClsFields =
12081 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +000012082 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +000012083 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012084 // Add ivar's to class's DeclContext.
12085 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12086 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012087 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012088 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +000012089 // Must enforce the rule that ivars in the base classes may not be
12090 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +000012091 if (ID->getSuperClass())
12092 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +000012093 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +000012094 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000012095 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012096 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12097 // Ivar declared in @implementation never belongs to the implementation.
12098 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +000012099 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +000012100 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012101 IMPDecl->setIvarLBraceLoc(LBrac);
12102 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012103 } else if (ObjCCategoryDecl *CDecl =
12104 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012105 // case of ivars in class extension; all other cases have been
12106 // reported as errors elsewhere.
12107 // FIXME. Class extension does not have a LocEnd field.
12108 // CDecl->setLocEnd(RBrac);
12109 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012110 // Diagnose redeclaration of private ivars.
12111 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012112 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012113 if (IDecl) {
12114 if (const ObjCIvarDecl *ClsIvar =
12115 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12116 Diag(ClsFields[i]->getLocation(),
12117 diag::err_duplicate_ivar_declaration);
12118 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12119 continue;
12120 }
Douglas Gregord3297242013-01-16 23:00:23 +000012121 for (ObjCInterfaceDecl::known_extensions_iterator
12122 Ext = IDecl->known_extensions_begin(),
12123 ExtEnd = IDecl->known_extensions_end();
12124 Ext != ExtEnd; ++Ext) {
12125 if (const ObjCIvarDecl *ClsExtIvar
12126 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012127 Diag(ClsFields[i]->getLocation(),
12128 diag::err_duplicate_ivar_declaration);
12129 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12130 continue;
12131 }
12132 }
12133 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012134 ClsFields[i]->setLexicalDeclContext(CDecl);
12135 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012136 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012137 CDecl->setIvarLBraceLoc(LBrac);
12138 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +000012139 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +000012140 }
Daniel Dunbar7d076642008-10-03 17:33:35 +000012141
12142 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000012143 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +000012144}
12145
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012146/// \brief Determine whether the given integral value is representable within
12147/// the given type T.
12148static bool isRepresentableIntegerValue(ASTContext &Context,
12149 llvm::APSInt &Value,
12150 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012151 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +000012152 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012153
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012154 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +000012155 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012156 --BitWidth;
12157 return Value.getActiveBits() <= BitWidth;
12158 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012159 return Value.getMinSignedBits() <= BitWidth;
12160}
12161
12162// \brief Given an integral type, return the next larger integral type
12163// (or a NULL type of no such type exists).
12164static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12165 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12166 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012167 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012168 const unsigned NumTypes = 4;
12169 QualType SignedIntegralTypes[NumTypes] = {
12170 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12171 };
12172 QualType UnsignedIntegralTypes[NumTypes] = {
12173 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12174 Context.UnsignedLongLongTy
12175 };
12176
12177 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +000012178 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12179 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012180 for (unsigned I = 0; I != NumTypes; ++I)
12181 if (Context.getTypeSize(Types[I]) > BitWidth)
12182 return Types[I];
12183
12184 return QualType();
12185}
12186
Douglas Gregor879fd492009-03-17 19:05:46 +000012187EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12188 EnumConstantDecl *LastEnumConst,
12189 SourceLocation IdLoc,
12190 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +000012191 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012192 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012193 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +000012194 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +000012195
12196 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12197 Val = 0;
12198
Eli Friedman19efa3e2011-12-06 00:10:34 +000012199 if (Val)
12200 Val = DefaultLvalueConversion(Val).take();
12201
Douglas Gregor4912c342009-11-06 00:03:12 +000012202 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012203 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +000012204 EltTy = Context.DependentTy;
12205 else {
Douglas Gregor4912c342009-11-06 00:03:12 +000012206 SourceLocation ExpLoc;
Richard Smith80ad52f2013-01-02 11:42:31 +000012207 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012208 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012209 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12210 // constant-expression in the enumerator-definition shall be a converted
12211 // constant expression of the underlying type.
12212 EltTy = Enum->getIntegerType();
12213 ExprResult Converted =
12214 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12215 CCEK_Enumerator);
12216 if (Converted.isInvalid())
12217 Val = 0;
12218 else
12219 Val = Converted.take();
12220 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +000012221 !(Val = VerifyIntegerConstantExpression(Val,
12222 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012223 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +000012224 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012225 if (Enum->isFixed()) {
12226 EltTy = Enum->getIntegerType();
12227
Richard Smith8ef7b202012-01-18 23:55:52 +000012228 // In Obj-C and Microsoft mode, require the enumeration value to be
12229 // representable in the underlying type of the enumeration. In C++11,
12230 // we perform a non-narrowing conversion as part of converted constant
12231 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +000012232 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012233 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +000012234 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +000012235 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +000012236 } else
12237 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +000012238 } else
John Wiegley429bb272011-04-08 18:41:53 +000012239 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +000012240 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012241 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012242 // If the underlying type is not fixed, the type of each enumerator
12243 // is the type of its initializing value:
12244 // - If an initializer is specified for an enumerator, the
12245 // initializing value has the same type as the expression.
12246 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +000012247 } else {
12248 // C99 6.7.2.2p2:
12249 // The expression that defines the value of an enumeration constant
12250 // shall be an integer constant expression that has a value
12251 // representable as an int.
12252
12253 // Complain if the value is not representable in an int.
12254 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12255 Diag(IdLoc, diag::ext_enum_value_not_int)
12256 << EnumVal.toString(10) << Val->getSourceRange()
12257 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12258 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12259 // Force the type of the expression to 'int'.
12260 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12261 }
12262 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012263 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012264 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012265 }
12266 }
Mike Stump1eb44332009-09-09 15:08:12 +000012267
Douglas Gregor879fd492009-03-17 19:05:46 +000012268 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012269 if (Enum->isDependentType())
12270 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012271 else if (!LastEnumConst) {
12272 // C++0x [dcl.enum]p5:
12273 // If the underlying type is not fixed, the type of each enumerator
12274 // is the type of its initializing value:
12275 // - If no initializer is specified for the first enumerator, the
12276 // initializing value has an unspecified integral type.
12277 //
12278 // GCC uses 'int' for its unspecified integral type, as does
12279 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012280 if (Enum->isFixed()) {
12281 EltTy = Enum->getIntegerType();
12282 }
12283 else {
12284 EltTy = Context.IntTy;
12285 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012286 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000012287 // Assign the last value + 1.
12288 EnumVal = LastEnumConst->getInitVal();
12289 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012290 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000012291
12292 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012293 if (EnumVal < LastEnumConst->getInitVal()) {
12294 // C++0x [dcl.enum]p5:
12295 // If the underlying type is not fixed, the type of each enumerator
12296 // is the type of its initializing value:
12297 //
12298 // - Otherwise the type of the initializing value is the same as
12299 // the type of the initializing value of the preceding enumerator
12300 // unless the incremented value is not representable in that type,
12301 // in which case the type is an unspecified integral type
12302 // sufficient to contain the incremented value. If no such type
12303 // exists, the program is ill-formed.
12304 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012305 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012306 // There is no integral type larger enough to represent this
12307 // value. Complain, then allow the value to wrap around.
12308 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000012309 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012310 ++EnumVal;
12311 if (Enum->isFixed())
12312 // When the underlying type is fixed, this is ill-formed.
12313 Diag(IdLoc, diag::err_enumerator_wrapped)
12314 << EnumVal.toString(10)
12315 << EltTy;
12316 else
12317 Diag(IdLoc, diag::warn_enumerator_too_large)
12318 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012319 } else {
12320 EltTy = T;
12321 }
12322
12323 // Retrieve the last enumerator's value, extent that type to the
12324 // type that is supposed to be large enough to represent the incremented
12325 // value, then increment.
12326 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000012327 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000012328 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012329 ++EnumVal;
12330
12331 // If we're not in C++, diagnose the overflow of enumerator values,
12332 // which in C99 means that the enumerator value is not representable in
12333 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12334 // permits enumerator values that are representable in some larger
12335 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000012336 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012337 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000012338 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012339 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12340 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12341 Diag(IdLoc, diag::ext_enum_value_not_int)
12342 << EnumVal.toString(10) << 1;
12343 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012344 }
12345 }
Mike Stump1eb44332009-09-09 15:08:12 +000012346
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012347 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012348 // Make the enumerator value match the signedness and size of the
12349 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000012350 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000012351 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012352 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012353
Douglas Gregor879fd492009-03-17 19:05:46 +000012354 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000012355 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000012356}
12357
12358
John McCall5b629aa2010-10-22 23:36:17 +000012359Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12360 SourceLocation IdLoc, IdentifierInfo *Id,
12361 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000012362 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000012363 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000012364 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000012365 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000012366
Chris Lattner31e05722007-08-26 06:24:45 +000012367 // The scope passed in may not be a decl scope. Zip up the scope tree until
12368 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000012369 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000012370
Reid Spencer5f016e22007-07-11 17:01:13 +000012371 // Verify that there isn't already something declared with this name in this
12372 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000012373 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000012374 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000012375 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000012376 // Maybe we will complain about the shadowed template parameter.
12377 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12378 // Just pretend that we didn't see the previous declaration.
12379 PrevDecl = 0;
12380 }
12381
12382 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012383 // When in C++, we may get a TagDecl with the same name; in this case the
12384 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000012385 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012386 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000012387 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012388 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000012389 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000012390 else
Chris Lattner3c73c412008-11-19 08:23:25 +000012391 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000012392 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000012393 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000012394 }
12395 }
12396
Aaron Ballmanf8167872012-07-19 03:12:23 +000012397 // C++ [class.mem]p15:
12398 // If T is the name of a class, then each of the following shall have a name
12399 // different from T:
12400 // - every enumerator of every member of class T that is an unscoped
12401 // enumerated type
Douglas Gregora6e937c2010-10-15 13:21:21 +000012402 if (CXXRecordDecl *Record
12403 = dyn_cast<CXXRecordDecl>(
12404 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballmanf8167872012-07-19 03:12:23 +000012405 if (!TheEnumDecl->isScoped() &&
12406 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregora6e937c2010-10-15 13:21:21 +000012407 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12408
John McCall5b629aa2010-10-22 23:36:17 +000012409 EnumConstantDecl *New =
12410 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000012411
John McCall92f88312010-01-23 00:46:32 +000012412 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000012413 // Process attributes.
12414 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12415
12416 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000012417 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000012418 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000012419 }
Douglas Gregor45579f52008-12-17 02:04:30 +000012420
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000012421 ActOnDocumentableDecl(New);
12422
John McCalld226f652010-08-21 09:40:31 +000012423 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000012424}
12425
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012426// Returns true when the enum initial expression does not trigger the
12427// duplicate enum warning. A few common cases are exempted as follows:
12428// Element2 = Element1
12429// Element2 = Element1 + 1
12430// Element2 = Element1 - 1
12431// Where Element2 and Element1 are from the same enum.
12432static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12433 Expr *InitExpr = ECD->getInitExpr();
12434 if (!InitExpr)
12435 return true;
12436 InitExpr = InitExpr->IgnoreImpCasts();
12437
12438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12439 if (!BO->isAdditiveOp())
12440 return true;
12441 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12442 if (!IL)
12443 return true;
12444 if (IL->getValue() != 1)
12445 return true;
12446
12447 InitExpr = BO->getLHS();
12448 }
12449
12450 // This checks if the elements are from the same enum.
12451 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12452 if (!DRE)
12453 return true;
12454
12455 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12456 if (!EnumConstant)
12457 return true;
12458
12459 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12460 Enum)
12461 return true;
12462
12463 return false;
12464}
12465
12466struct DupKey {
12467 int64_t val;
12468 bool isTombstoneOrEmptyKey;
12469 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12470 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12471};
12472
12473static DupKey GetDupKey(const llvm::APSInt& Val) {
12474 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12475 false);
12476}
12477
12478struct DenseMapInfoDupKey {
12479 static DupKey getEmptyKey() { return DupKey(0, true); }
12480 static DupKey getTombstoneKey() { return DupKey(1, true); }
12481 static unsigned getHashValue(const DupKey Key) {
12482 return (unsigned)(Key.val * 37);
12483 }
12484 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12485 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12486 LHS.val == RHS.val;
12487 }
12488};
12489
12490// Emits a warning when an element is implicitly set a value that
12491// a previous element has already been set to.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012492static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12493 EnumDecl *Enum,
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012494 QualType EnumType) {
12495 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12496 Enum->getLocation()) ==
12497 DiagnosticsEngine::Ignored)
12498 return;
12499 // Avoid anonymous enums
12500 if (!Enum->getIdentifier())
12501 return;
12502
12503 // Only check for small enums.
12504 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12505 return;
12506
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012507 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12508 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012509
12510 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12511 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12512 ValueToVectorMap;
12513
12514 DuplicatesVector DupVector;
12515 ValueToVectorMap EnumMap;
12516
12517 // Populate the EnumMap with all values represented by enum constants without
12518 // an initialier.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012519 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramerefac8da2013-04-07 14:10:40 +000012520 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012521
12522 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12523 // this constant. Skip this enum since it may be ill-formed.
12524 if (!ECD) {
12525 return;
12526 }
12527
12528 if (ECD->getInitExpr())
12529 continue;
12530
12531 DupKey Key = GetDupKey(ECD->getInitVal());
12532 DeclOrVector &Entry = EnumMap[Key];
12533
12534 // First time encountering this value.
12535 if (Entry.isNull())
12536 Entry = ECD;
12537 }
12538
12539 // Create vectors for any values that has duplicates.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012540 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012541 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12542 if (!ValidDuplicateEnum(ECD, Enum))
12543 continue;
12544
12545 DupKey Key = GetDupKey(ECD->getInitVal());
12546
12547 DeclOrVector& Entry = EnumMap[Key];
12548 if (Entry.isNull())
12549 continue;
12550
12551 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12552 // Ensure constants are different.
12553 if (D == ECD)
12554 continue;
12555
12556 // Create new vector and push values onto it.
12557 ECDVector *Vec = new ECDVector();
12558 Vec->push_back(D);
12559 Vec->push_back(ECD);
12560
12561 // Update entry to point to the duplicates vector.
12562 Entry = Vec;
12563
12564 // Store the vector somewhere we can consult later for quick emission of
12565 // diagnostics.
12566 DupVector.push_back(Vec);
12567 continue;
12568 }
12569
12570 ECDVector *Vec = Entry.get<ECDVector*>();
12571 // Make sure constants are not added more than once.
12572 if (*Vec->begin() == ECD)
12573 continue;
12574
12575 Vec->push_back(ECD);
12576 }
12577
12578 // Emit diagnostics.
12579 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12580 DupVectorEnd = DupVector.end();
12581 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12582 ECDVector *Vec = *DupVectorIter;
12583 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12584
12585 // Emit warning for one enum constant.
12586 ECDVector::iterator I = Vec->begin();
12587 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12588 << (*I)->getName() << (*I)->getInitVal().toString(10)
12589 << (*I)->getSourceRange();
12590 ++I;
12591
12592 // Emit one note for each of the remaining enum constants with
12593 // the same value.
12594 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12595 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12596 << (*I)->getName() << (*I)->getInitVal().toString(10)
12597 << (*I)->getSourceRange();
12598 delete Vec;
12599 }
12600}
12601
Mike Stumpc6e35aa2009-05-16 07:06:02 +000012602void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000012603 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012604 ArrayRef<Decl *> Elements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012605 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000012606 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000012607 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012608
12609 if (Attr)
12610 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000012611
Eli Friedmaned0716b2009-12-11 01:34:50 +000012612 if (Enum->isDependentType()) {
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012613 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012614 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012615 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012616 if (!ECD) continue;
12617
12618 ECD->setType(EnumType);
12619 }
12620
John McCall1b5a6182010-05-06 08:49:23 +000012621 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012622 return;
12623 }
12624
Chris Lattnere37f0be2007-08-28 05:10:31 +000012625 // TODO: If the result value doesn't fit in an int, it must be a long or long
12626 // long value. ISO C does not support this, but GCC does as an extension,
12627 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012628 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12629 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12630 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012631
Chris Lattnerac609682007-08-28 06:15:15 +000012632 // Verify that all the values are okay, compute the size of the values, and
12633 // reverse the list.
12634 unsigned NumNegativeBits = 0;
12635 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000012636
Chris Lattnerac609682007-08-28 06:15:15 +000012637 // Keep track of whether all elements have type int.
12638 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000012639
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012640 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012641 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012642 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000012643 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000012644
Chris Lattner211a30e2007-08-28 05:27:00 +000012645 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000012646
Chris Lattnerac609682007-08-28 06:15:15 +000012647 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000012648 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000012649 NumPositiveBits = std::max(NumPositiveBits,
12650 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000012651 else
Chris Lattner21dd8212008-01-14 21:47:29 +000012652 NumNegativeBits = std::max(NumNegativeBits,
12653 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000012654
Chris Lattnerac609682007-08-28 06:15:15 +000012655 // Keep track of whether every enum element has type int (very commmon).
12656 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000012657 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000012658 }
Mike Stump1eb44332009-09-09 15:08:12 +000012659
Chris Lattnerac609682007-08-28 06:15:15 +000012660 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000012661 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012662 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012663
John McCall842aef82009-12-09 09:09:27 +000012664 // C++0x N3000 [conv.prom]p3:
12665 // An rvalue of an unscoped enumeration type whose underlying
12666 // type is not fixed can be converted to an rvalue of the first
12667 // of the following types that can represent all the values of
12668 // the enumeration: int, unsigned int, long int, unsigned long
12669 // int, long long int, or unsigned long long int.
12670 // C99 6.4.4.3p2:
12671 // An identifier declared as an enumeration constant has type int.
12672 // The C99 rule is modified by a gcc extension
12673 QualType BestPromotionType;
12674
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012675 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000012676 // -fshort-enums is the equivalent to specifying the packed attribute on all
12677 // enum definitions.
12678 if (LangOpts.ShortEnums)
12679 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012680
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012681 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000012682 BestType = Enum->getIntegerType();
12683 if (BestType->isPromotableIntegerType())
12684 BestPromotionType = Context.getPromotedIntegerType(BestType);
12685 else
12686 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000012687 // We don't need to set BestWidth, because BestType is going to be the type
12688 // of the enumerators, but we do anyway because otherwise some compilers
12689 // warn that it might be used uninitialized.
12690 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012691 }
12692 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000012693 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000012694 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012695 // If it's packed, check also if it fits a char or a short.
12696 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012697 BestType = Context.SignedCharTy;
12698 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000012699 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012700 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012701 BestType = Context.ShortTy;
12702 BestWidth = ShortWidth;
12703 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012704 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012705 BestWidth = IntWidth;
12706 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012707 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012708
John McCall842aef82009-12-09 09:09:27 +000012709 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012710 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000012711 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012712 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012713
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012714 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000012715 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12716 BestType = Context.LongLongTy;
12717 }
12718 }
John McCall842aef82009-12-09 09:09:27 +000012719 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000012720 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012721 // If there is no negative value, figure out the smallest type that fits
12722 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012723 // If it's packed, check also if it fits a char or a short.
12724 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012725 BestType = Context.UnsignedCharTy;
12726 BestPromotionType = Context.IntTy;
12727 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012728 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012729 BestType = Context.UnsignedShortTy;
12730 BestPromotionType = Context.IntTy;
12731 BestWidth = ShortWidth;
12732 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012733 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012734 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012735 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012736 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012737 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012738 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012739 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000012740 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012741 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012742 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012743 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000012744 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012745 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012746 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000012747 "How could an initializer get larger than ULL?");
12748 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012749 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012750 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012751 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000012752 }
12753 }
Mike Stump1eb44332009-09-09 15:08:12 +000012754
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012755 // Loop over all of the enumerator constants, changing their types to match
12756 // the type of the enum if needed.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012757 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +000012758 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012759 if (!ECD) continue; // Already issued a diagnostic.
12760
12761 // Standard C says the enumerators have int type, but we allow, as an
12762 // extension, the enumerators to be larger than int size. If each
12763 // enumerator value fits in an int, type it as an int, otherwise type it the
12764 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12765 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012766
12767 // Determine whether the value fits into an int.
12768 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012769
12770 // If it fits into an integer type, force it. Otherwise force it to match
12771 // the enum decl type.
12772 QualType NewTy;
12773 unsigned NewWidth;
12774 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000012775 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000012776 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012777 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012778 NewTy = Context.IntTy;
12779 NewWidth = IntWidth;
12780 NewSign = true;
12781 } else if (ECD->getType() == BestType) {
12782 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000012783 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012784 // C++ [dcl.enum]p4: Following the closing brace of an
12785 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012786 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012787 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012788 continue;
12789 } else {
12790 NewTy = BestType;
12791 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000012792 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012793 }
12794
12795 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000012796 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012797 InitVal.setIsSigned(NewSign);
12798 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000012799
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012800 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000012801 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000012802 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000012803 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000012804 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000012805 ECD->getInitExpr(),
12806 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000012807 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000012808 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012809 // C++ [dcl.enum]p4: Following the closing brace of an
12810 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012811 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012812 ECD->setType(EnumType);
12813 else
12814 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012815 }
Mike Stump1eb44332009-09-09 15:08:12 +000012816
John McCall1b5a6182010-05-06 08:49:23 +000012817 Enum->completeDefinition(BestType, BestPromotionType,
12818 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000012819
12820 // If we're declaring a function, ensure this decl isn't forgotten about -
12821 // it needs to go into the function scope.
12822 if (InFunctionDeclarator)
12823 DeclsInPrototypeScope.push_back(Enum);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012824
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012825 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smithbe507b62013-02-01 08:12:08 +000012826
12827 // Now that the enum type is defined, ensure it's not been underaligned.
12828 if (Enum->hasAttrs())
12829 CheckAlignasUnderalignment(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +000012830}
12831
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012832Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12833 SourceLocation StartLoc,
12834 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000012835 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000012836
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000012837 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012838 AsmString, StartLoc,
12839 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012840 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000012841 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000012842}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012843
Douglas Gregor5948ae12012-01-03 18:04:46 +000012844DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12845 SourceLocation ImportLoc,
12846 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000012847 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000012848 Module::AllVisible,
12849 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000012850 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012851 return true;
12852
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012853 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregor15de72c2011-12-02 23:23:56 +000012854 Module *ModCheck = Mod;
12855 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12856 // If we've run out of module parents, just drop the remaining identifiers.
12857 // We need the length to be consistent.
12858 if (!ModCheck)
12859 break;
12860 ModCheck = ModCheck->Parent;
12861
12862 IdentifierLocs.push_back(Path[I].second);
12863 }
12864
12865 ImportDecl *Import = ImportDecl::Create(Context,
12866 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000012867 AtLoc.isValid()? AtLoc : ImportLoc,
12868 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000012869 Context.getTranslationUnitDecl()->addDecl(Import);
12870 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012871}
12872
Douglas Gregorca2ab452013-01-12 01:29:50 +000012873void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12874 // Create the implicit import declaration.
12875 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12876 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12877 Loc, Mod, Loc);
12878 TU->addDecl(ImportD);
12879 Consumer.HandleImplicitImportDecl(ImportD);
12880
12881 // Make the module visible.
Douglas Gregor906d66a2013-03-20 21:10:35 +000012882 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12883 /*Complain=*/false);
Douglas Gregorca2ab452013-01-12 01:29:50 +000012884}
12885
David Chisnall5f3c1632012-02-18 16:12:34 +000012886void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12887 IdentifierInfo* AliasName,
12888 SourceLocation PragmaLoc,
12889 SourceLocation NameLoc,
12890 SourceLocation AliasNameLoc) {
12891 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12892 LookupOrdinaryName);
12893 AsmLabelAttr *Attr =
12894 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000012895
12896 if (PrevDecl)
12897 PrevDecl->addAttr(Attr);
12898 else
12899 (void)ExtnameUndeclaredIdentifiers.insert(
12900 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12901}
12902
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012903void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12904 SourceLocation PragmaLoc,
12905 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012906 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012907
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012908 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000012909 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000012910 } else {
12911 (void)WeakUndeclaredIdentifiers.insert(
12912 std::pair<IdentifierInfo*,WeakInfo>
12913 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012914 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012915}
12916
12917void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12918 IdentifierInfo* AliasName,
12919 SourceLocation PragmaLoc,
12920 SourceLocation NameLoc,
12921 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012922 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12923 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000012924 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012925
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012926 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000012927 if (!PrevDecl->hasAttr<AliasAttr>())
12928 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000012929 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000012930 } else {
12931 (void)WeakUndeclaredIdentifiers.insert(
12932 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012933 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012934}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000012935
12936Decl *Sema::getObjCDeclContext() const {
12937 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12938}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012939
12940AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000012941 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012942 return D->getAvailability();
12943}