blob: 6a5d608c7b2e87d493267f3a8d89079f28c2f703 [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"
Faisal Valic00e4192013-11-07 05:17:06 +000043#include "clang/Sema/Template.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000044#include "llvm/ADT/SmallString.h"
John McCall66755862009-12-24 09:58:38 +000045#include "llvm/ADT/Triple.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000046#include <algorithm>
Douglas Gregor9a8c9a22009-09-28 21:14:19 +000047#include <cstring>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000048#include <functional>
Reid Spencer5f016e22007-07-11 17:01:13 +000049using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000050using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000051
Richard Smithc89edf52011-07-01 19:46:12 +000052Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
53 if (OwnedType) {
54 Decl *Group[2] = { OwnedType, Ptr };
55 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
56 }
57
John McCalld226f652010-08-21 09:40:31 +000058 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner682bf922009-03-29 16:50:03 +000059}
60
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000061namespace {
62
63class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64 public:
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000065 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
66 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000067 WantExpressionKeywords = false;
68 WantCXXNamedCasts = false;
69 WantRemainingKeywords = false;
70 }
71
72 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
73 if (NamedDecl *ND = candidate.getCorrectionDecl())
74 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
75 (AllowInvalidDecl || !ND->isInvalidDecl());
76 else
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000077 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000078 }
79
80 private:
81 bool AllowInvalidDecl;
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +000082 bool WantClassName;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +000083};
84
85}
86
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +000087/// \brief Determine whether the token kind starts a simple-type-specifier.
88bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
89 switch (Kind) {
90 // FIXME: Take into account the current language when deciding whether a
91 // token kind is a valid type specifier
92 case tok::kw_short:
93 case tok::kw_long:
94 case tok::kw___int64:
95 case tok::kw___int128:
96 case tok::kw_signed:
97 case tok::kw_unsigned:
98 case tok::kw_void:
99 case tok::kw_char:
100 case tok::kw_int:
101 case tok::kw_half:
102 case tok::kw_float:
103 case tok::kw_double:
104 case tok::kw_wchar_t:
105 case tok::kw_bool:
106 case tok::kw___underlying_type:
107 return true;
108
109 case tok::annot_typename:
110 case tok::kw_char16_t:
111 case tok::kw_char32_t:
112 case tok::kw_typeof:
David Majnemerff989a82013-09-22 01:24:26 +0000113 case tok::annot_decltype:
Kaelyn Uhrain7bf33402012-06-15 23:45:51 +0000114 case tok::kw_decltype:
115 return getLangOpts().CPlusPlus;
116
117 default:
118 break;
119 }
120
121 return false;
122}
123
Douglas Gregord6efafa2009-02-04 19:16:12 +0000124/// \brief If the identifier refers to a type name within this scope,
125/// return the declaration of that type.
126///
127/// This routine performs ordinary name lookup of the identifier II
128/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000129/// determine whether the name refers to a type. If so, returns an
130/// opaque pointer (actually a QualType) corresponding to that
131/// type. Otherwise, returns NULL.
Dmitri Gribenko8eead162013-05-03 13:12:11 +0000132ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallb3d87482010-08-24 05:47:05 +0000133 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000134 bool isClassName, bool HasTrailingDot,
Douglas Gregor9e876872011-03-01 18:12:44 +0000135 ParsedType ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000136 bool IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000137 bool WantNontrivialTypeSourceInfo,
138 IdentifierInfo **CorrectedII) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000139 // Determine where we will perform name lookup.
140 DeclContext *LookupCtx = 0;
141 if (ObjectTypePtr) {
John McCallb3d87482010-08-24 05:47:05 +0000142 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000143 if (ObjectType->isRecordType())
144 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskinedc28772010-04-07 23:29:58 +0000145 } else if (SS && SS->isNotEmpty()) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000146 LookupCtx = computeDeclContext(*SS, false);
147
148 if (!LookupCtx) {
149 if (isDependentScopeSpecifier(*SS)) {
150 // C++ [temp.res]p3:
151 // A qualified-id that refers to a type and in which the
152 // nested-name-specifier depends on a template-parameter (14.6.2)
153 // shall be prefixed by the keyword typename to indicate that the
154 // qualified-id denotes a type, forming an
155 // elaborated-type-specifier (7.1.5.3).
156 //
157 // We therefore do not perform any name lookup if the result would
158 // refer to a member of an unknown specialization.
Richard Smithc5a89a12012-04-02 01:30:27 +0000159 if (!isClassName && !IsCtorOrDtorName)
John McCallb3d87482010-08-24 05:47:05 +0000160 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000161
John McCall33500952010-06-11 00:33:02 +0000162 // We know from the grammar that this name refers to a type,
163 // so build a dependent node to describe the type.
Douglas Gregor9e876872011-03-01 18:12:44 +0000164 if (WantNontrivialTypeSourceInfo)
165 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
166
167 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallb3d87482010-08-24 05:47:05 +0000168 QualType T =
Douglas Gregor9e876872011-03-01 18:12:44 +0000169 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +0000170 II, NameLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +0000171
172 return ParsedType::make(T);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000173 }
174
John McCallb3d87482010-08-24 05:47:05 +0000175 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000176 }
177
John McCall77bb1aa2010-05-01 00:40:08 +0000178 if (!LookupCtx->isDependentContext() &&
179 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallb3d87482010-08-24 05:47:05 +0000180 return ParsedType();
Douglas Gregor42c39f32009-08-26 18:27:52 +0000181 }
Eli Friedman0f0615b2009-12-21 01:42:38 +0000182
183 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
184 // lookup for class-names.
185 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
186 LookupOrdinaryName;
187 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000188 if (LookupCtx) {
189 // Perform "qualified" name lookup into the declaration context we
190 // computed, which is either the type of the base of a member access
191 // expression or the declaration context associated with a prior
192 // nested-name-specifier.
193 LookupQualifiedName(Result, LookupCtx);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000194
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000195 if (ObjectTypePtr && Result.empty()) {
196 // C++ [basic.lookup.classref]p3:
197 // If the unqualified-id is ~type-name, the type-name is looked up
198 // in the context of the entire postfix-expression. If the type T of
199 // the object expression is of a class type C, the type-name is also
200 // looked up in the scope of class C. At least one of the lookups shall
201 // find a name that refers to (possibly cv-qualified) T.
202 LookupName(Result, S);
203 }
204 } else {
205 // Perform unqualified name lookup.
206 LookupName(Result, S);
207 }
208
Chris Lattner22bd9052009-02-16 22:07:16 +0000209 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000210 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +0000211 case LookupResult::NotFound:
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000212 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000213 if (CorrectedII) {
Kaelyn Uhrainc1fb5422012-06-22 23:37:05 +0000214 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000215 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000216 Kind, S, SS, Validator);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000217 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
218 TemplateTy Template;
219 bool MemberOfUnknownSpecialization;
220 UnqualifiedId TemplateName;
221 TemplateName.setIdentifier(NewII, NameLoc);
222 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
223 CXXScopeSpec NewSS, *NewSSPtr = SS;
224 if (SS && NNS) {
225 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226 NewSSPtr = &NewSS;
227 }
228 if (Correction && (NNS || NewII != &II) &&
229 // Ignore a correction to a template type as the to-be-corrected
230 // identifier is not a template (typo correction for template names
231 // is handled elsewhere).
David Blaikie4e4d0842012-03-11 07:00:24 +0000232 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000233 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
234 false, Template, MemberOfUnknownSpecialization))) {
235 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
236 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000237 IsCtorOrDtorName,
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000238 WantNontrivialTypeSourceInfo);
239 if (Ty) {
Richard Smith2d670972013-08-17 00:46:16 +0000240 diagnoseTypo(Correction,
241 PDiag(diag::err_unknown_type_or_class_name_suggest)
242 << Result.getLookupName() << isClassName);
Kaelyn Uhrainfac94672011-10-11 01:02:41 +0000243 if (SS && NNS)
244 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
245 *CorrectedII = NewII;
246 return Ty;
247 }
248 }
249 }
250 // If typo correction failed or was not performed, fall through
Chris Lattner22bd9052009-02-16 22:07:16 +0000251 case LookupResult::FoundOverloaded:
John McCall7ba107a2009-11-18 02:36:19 +0000252 case LookupResult::FoundUnresolvedValue:
John McCallc373d482010-01-27 01:50:18 +0000253 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000254 return ParsedType();
Douglas Gregorb696ea32009-02-04 17:00:24 +0000255
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000256 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000257 // Recover from type-hiding ambiguities by hiding the type. We'll
258 // do the lookup again when looking for an object, and we can
259 // diagnose the error then. If we don't do this, then the error
260 // about hiding the type will be immediately followed by an error
261 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000262 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
263 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000264 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000265 }
John McCall6e247262009-10-10 05:48:19 +0000266
Douglas Gregor31a19b62009-04-01 21:51:26 +0000267 // Look to see if we have a type anywhere in the list of results.
268 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
269 Res != ResEnd; ++Res) {
270 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000271 if (!IIDecl ||
272 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000273 IIDecl->getLocation().getRawEncoding())
274 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000275 }
276 }
277
278 if (!IIDecl) {
279 // None of the entities we found is a type, so there is no way
280 // to even assume that the result is a type. In this case, don't
281 // complain about the ambiguity. The parser will either try to
282 // perform this lookup again (e.g., as an object name), which
283 // will produce the ambiguity, or will complain that it expected
284 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000285 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000286 return ParsedType();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000287 }
288
289 // We found a type within the ambiguous lookup; diagnose the
290 // ambiguity and then return that type. This might be the right
291 // answer, or it might not be, but it suppresses any attempt to
292 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000293 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000294
Chris Lattner22bd9052009-02-16 22:07:16 +0000295 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000296 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000297 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000298 }
299
Chris Lattner10ca3372009-10-25 17:16:46 +0000300 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000301
Chris Lattner10ca3372009-10-25 17:16:46 +0000302 QualType T;
303 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000304 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000305
Chris Lattner10ca3372009-10-25 17:16:46 +0000306 if (T.isNull())
307 T = Context.getTypeDeclType(TD);
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000308
309 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
310 // constructor or destructor name (in such a case, the scope specifier
311 // will be attached to the enclosing Expr or Decl node).
312 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor9e876872011-03-01 18:12:44 +0000313 if (WantNontrivialTypeSourceInfo) {
314 // Construct a type with type-source information.
315 TypeLocBuilder Builder;
316 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
317
318 T = getElaboratedType(ETK_None, *SS, T);
319 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara38a42912012-02-06 19:09:27 +0000320 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor9e876872011-03-01 18:12:44 +0000321 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
322 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
323 } else {
324 T = getElaboratedType(ETK_None, *SS, T);
325 }
326 }
Chris Lattner10ca3372009-10-25 17:16:46 +0000327 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian02b0d652011-03-08 19:12:46 +0000328 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000329 if (!HasTrailingDot)
330 T = Context.getObjCInterfaceType(IDecl);
331 }
332
333 if (T.isNull()) {
John McCalla24dc2e2009-11-17 02:14:36 +0000334 // If it's not plausibly a type, suppress diagnostics.
335 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000336 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000337 }
John McCallb3d87482010-08-24 05:47:05 +0000338 return ParsedType::make(T);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339}
340
Chris Lattner4c97d762009-04-12 21:49:30 +0000341/// isTagName() - This method is called *for error recovery purposes only*
342/// to determine if the specified name is a valid tag name ("struct foo"). If
343/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matos6666ed42012-08-31 18:45:21 +0000344/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
345/// cases in C where the user forgot to specify the tag.
Chris Lattner4c97d762009-04-12 21:49:30 +0000346DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
347 // Do a tag name lookup in this scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000348 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
349 LookupName(R, S, false);
350 R.suppressDiagnostics();
351 if (R.getResultKind() == LookupResult::Found)
John McCall1bcee0a2009-12-02 08:25:40 +0000352 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattner4c97d762009-04-12 21:49:30 +0000353 switch (TD->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000354 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matos6666ed42012-08-31 18:45:21 +0000355 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000356 case TTK_Union: return DeclSpec::TST_union;
357 case TTK_Class: return DeclSpec::TST_class;
358 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattner4c97d762009-04-12 21:49:30 +0000359 }
360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Chris Lattner4c97d762009-04-12 21:49:30 +0000362 return DeclSpec::TST_unspecified;
363}
364
Francois Pichet6943e9b2011-04-13 02:38:49 +0000365/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
366/// if a CXXScopeSpec's type is equal to the type of one of the base classes
367/// then downgrade the missing typename error to a warning.
368/// This is needed for MSVC compatibility; Example:
369/// @code
370/// template<class T> class A {
371/// public:
372/// typedef int TYPE;
373/// };
374/// template<class T> class B : public A<T> {
375/// public:
376/// A<T>::TYPE a; // no typename required because A<T> is a base class.
377/// };
378/// @endcode
Francois Pichetf11dbe92011-10-11 01:50:09 +0000379bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000380 if (CurContext->isRecord()) {
Francois Pichet3441a522011-04-13 02:44:57 +0000381 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000382
383 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
384 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
385 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
386 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
387 return true;
Francois Pichetf11dbe92011-10-11 01:50:09 +0000388 return S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000389 }
Francois Pichetf11dbe92011-10-11 01:50:09 +0000390 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet6943e9b2011-04-13 02:38:49 +0000391}
392
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000393bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregora786fdb2009-10-13 23:27:22 +0000394 SourceLocation IILoc,
395 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000396 CXXScopeSpec *SS,
John McCallb3d87482010-08-24 05:47:05 +0000397 ParsedType &SuggestedType) {
Douglas Gregora786fdb2009-10-13 23:27:22 +0000398 // We don't have anything to suggest (yet).
John McCallb3d87482010-08-24 05:47:05 +0000399 SuggestedType = ParsedType();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000400
Douglas Gregor546be3c2009-12-30 17:04:44 +0000401 // There may have been a typo in the name of the type. Look up typo
402 // results, in case we have something that we can suggest.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000403 TypeNameValidatorCCC Validator(false);
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000404 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000405 LookupOrdinaryName, S, SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000406 Validator)) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000407 if (Corrected.isKeyword()) {
408 // We corrected to a keyword.
Richard Smith2d670972013-08-17 00:46:16 +0000409 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
410 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000411 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000412 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000413 if (!SS || !SS->isSet()) {
Richard Smith2d670972013-08-17 00:46:16 +0000414 diagnoseTypo(Corrected,
415 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000416 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +0000417 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
418 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000419 II->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000420 diagnoseTypo(Corrected,
421 PDiag(diag::err_unknown_nested_typename_suggest)
422 << II << DC << DroppedSpecifier << SS->getRange());
423 } else {
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000424 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000425 }
Douglas Gregor546be3c2009-12-30 17:04:44 +0000426
Kaelyn Uhraina934c312013-09-26 21:13:05 +0000427 CXXScopeSpec tmpSS;
428 if (Corrected.getCorrectionSpecifier())
429 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
430 SourceRange(IILoc));
Richard Smith2d670972013-08-17 00:46:16 +0000431 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhraina934c312013-09-26 21:13:05 +0000432 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
433 false, ParsedType(),
Abramo Bagnarafad03b72012-01-27 08:46:19 +0000434 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000435 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor546be3c2009-12-30 17:04:44 +0000436 }
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +0000437 return true;
Douglas Gregor546be3c2009-12-30 17:04:44 +0000438 }
439
David Blaikie4e4d0842012-03-11 07:00:24 +0000440 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000441 // See if II is a class template that the user forgot to pass arguments to.
442 UnqualifiedId Name;
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000443 Name.setIdentifier(II, IILoc);
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000444 CXXScopeSpec EmptySS;
445 TemplateTy TemplateResult;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000446 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000447 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000448 Name, ParsedType(), true, TemplateResult,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000449 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov18062392013-08-27 13:15:56 +0000450 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000451 Diag(IILoc, diag::err_template_missing_args) << TplName;
452 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
453 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
454 << TplDecl->getTemplateParameters()->getSourceRange();
455 }
456 return true;
457 }
458 }
459
Douglas Gregora786fdb2009-10-13 23:27:22 +0000460 // FIXME: Should we move the logic that tries to recover from a missing tag
461 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
462
Douglas Gregor546be3c2009-12-30 17:04:44 +0000463 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000464 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregora786fdb2009-10-13 23:27:22 +0000465 else if (DeclContext *DC = computeDeclContext(*SS, false))
466 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000467 << II << DC << SS->getRange();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000468 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet6943e9b2011-04-13 02:38:49 +0000469 unsigned DiagID = diag::err_typename_missing;
David Blaikie4e4d0842012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichetcf320c62011-04-22 08:25:24 +0000471 DiagID = diag::warn_typename_missing;
Francois Pichet6943e9b2011-04-13 02:38:49 +0000472
473 Diag(SS->getRange().getBegin(), DiagID)
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000474 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
Douglas Gregora786fdb2009-10-13 23:27:22 +0000475 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregor849b2432010-03-31 17:46:05 +0000476 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrain50dc12a2012-06-15 23:45:58 +0000477 SuggestedType = ActOnTypenameType(S, SourceLocation(),
478 *SS, *II, IILoc).get();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000479 } else {
480 assert(SS && SS->isInvalid() &&
481 "Invalid scope specifier has already been diagnosed");
482 }
483
484 return true;
485}
Chris Lattner4c97d762009-04-12 21:49:30 +0000486
Douglas Gregor312eadb2011-04-24 05:37:28 +0000487/// \brief Determine whether the given result set contains either a type name
488/// or
489static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000490 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000491 NextToken.is(tok::less);
492
493 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
494 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
495 return true;
496
497 if (CheckTemplate && isa<TemplateDecl>(*I))
498 return true;
499 }
500
501 return false;
502}
503
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000504static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
505 Scope *S, CXXScopeSpec &SS,
506 IdentifierInfo *&Name,
507 SourceLocation NameLoc) {
Richard Smith69e48262012-09-06 01:37:56 +0000508 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
509 SemaRef.LookupParsedName(R, S, &SS);
510 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000511 const char *TagName = 0;
512 const char *FixItTagName = 0;
513 switch (Tag->getTagKind()) {
514 case TTK_Class:
515 TagName = "class";
516 FixItTagName = "class ";
517 break;
518
519 case TTK_Enum:
520 TagName = "enum";
521 FixItTagName = "enum ";
522 break;
523
524 case TTK_Struct:
525 TagName = "struct";
526 FixItTagName = "struct ";
527 break;
528
Joao Matos6666ed42012-08-31 18:45:21 +0000529 case TTK_Interface:
530 TagName = "__interface";
531 FixItTagName = "__interface ";
532 break;
533
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000534 case TTK_Union:
535 TagName = "union";
536 FixItTagName = "union ";
537 break;
538 }
539
540 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
541 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
542 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
543
Richard Smith69e48262012-09-06 01:37:56 +0000544 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
545 I != IEnd; ++I)
546 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
547 << Name << TagName;
548
549 // Replace lookup results with just the tag decl.
550 Result.clear(Sema::LookupTagName);
551 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000552 return true;
553 }
554
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000555 return false;
556}
557
Richard Smith05766812012-08-18 00:55:03 +0000558/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
559static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
560 QualType T, SourceLocation NameLoc) {
561 ASTContext &Context = S.Context;
562
563 TypeLocBuilder Builder;
564 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
565
566 T = S.getElaboratedType(ETK_None, SS, T);
567 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
568 ElabTL.setElaboratedKeywordLoc(SourceLocation());
569 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
570 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
571}
572
Douglas Gregor312eadb2011-04-24 05:37:28 +0000573Sema::NameClassification Sema::ClassifyName(Scope *S,
574 CXXScopeSpec &SS,
575 IdentifierInfo *&Name,
576 SourceLocation NameLoc,
Richard Smith05766812012-08-18 00:55:03 +0000577 const Token &NextToken,
578 bool IsAddressOfOperand,
579 CorrectionCandidateCallback *CCC) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000580 DeclarationNameInfo NameInfo(Name, NameLoc);
581 ObjCMethodDecl *CurMethod = getCurMethodDecl();
582
583 if (NextToken.is(tok::coloncolon)) {
584 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
585 QualType(), false, SS, 0, false);
586
587 }
588
589 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
590 LookupParsedName(Result, S, &SS, !CurMethod);
591
592 // Perform lookup for Objective-C instance variables (including automatically
593 // synthesized instance variables), if we're in an Objective-C method.
594 // FIXME: This lookup really, really needs to be folded in to the normal
595 // unqualified lookup mechanism.
596 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
597 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorec385cf2011-04-25 15:05:41 +0000598 if (E.get() || E.isInvalid())
Douglas Gregor312eadb2011-04-24 05:37:28 +0000599 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000600 }
601
602 bool SecondTry = false;
603 bool IsFilteredTemplateName = false;
604
605Corrected:
606 switch (Result.getResultKind()) {
607 case LookupResult::NotFound:
608 // If an unqualified-id is followed by a '(', then we have a function
609 // call.
610 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
611 // In C++, this is an ADL-only call.
612 // FIXME: Reference?
David Blaikie4e4d0842012-03-11 07:00:24 +0000613 if (getLangOpts().CPlusPlus)
Douglas Gregor312eadb2011-04-24 05:37:28 +0000614 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
615
616 // C90 6.3.2.2:
617 // If the expression that precedes the parenthesized argument list in a
618 // function call consists solely of an identifier, and if no
619 // declaration is visible for this identifier, the identifier is
620 // implicitly declared exactly as if, in the innermost block containing
621 // the function call, the declaration
622 //
623 // extern int identifier ();
624 //
625 // appeared.
626 //
627 // We also allow this in C99 as an extension.
628 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
629 Result.addDecl(D);
630 Result.resolveKind();
631 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
632 }
633 }
634
635 // In C, we first see whether there is a tag type by the same name, in
636 // which case it's likely that the user just forget to write "enum",
637 // "struct", or "union".
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000638 if (!getLangOpts().CPlusPlus && !SecondTry &&
639 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
640 break;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000641 }
642
643 // Perform typo correction to determine if there is another name that is
644 // close to this name.
Richard Smith05766812012-08-18 00:55:03 +0000645 if (!SecondTry && CCC) {
Douglas Gregor3a348c82011-07-14 04:54:23 +0000646 SecondTry = true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000647 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikied662a792011-10-19 22:56:21 +0000648 Result.getLookupKind(), S,
Richard Smith05766812012-08-18 00:55:03 +0000649 &SS, *CCC)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000650 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
651 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smith2d670972013-08-17 00:46:16 +0000652
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000653 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor3b887352011-04-27 04:48:22 +0000654 NamedDecl *UnderlyingFirstDecl
655 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikie4e4d0842012-03-11 07:00:24 +0000656 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000657 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor27766d22011-04-27 03:47:06 +0000658 UnqualifiedDiag = diag::err_no_template_suggest;
659 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor3b887352011-04-27 04:48:22 +0000660 } else if (UnderlyingFirstDecl &&
661 (isa<TypeDecl>(UnderlyingFirstDecl) ||
662 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
663 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie30262b72013-03-21 21:35:15 +0000664 UnqualifiedDiag = diag::err_unknown_typename_suggest;
665 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
666 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000667
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000668 if (SS.isEmpty()) {
Richard Smith2d670972013-08-17 00:46:16 +0000669 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000670 } else {// FIXME: is this even reachable? Test it.
Richard Smith2d670972013-08-17 00:46:16 +0000671 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
672 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000673 Name->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +0000674 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
675 << Name << computeDeclContext(SS, false)
676 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000677 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000678
679 // Update the name, so that the caller has the new name.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000680 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smith2d670972013-08-17 00:46:16 +0000681
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000682 // Typo correction corrected to a keyword.
683 if (Corrected.isKeyword())
Richard Smith2d670972013-08-17 00:46:16 +0000684 return Name;
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000685
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000686 // Also update the LookupResult...
687 // FIXME: This should probably go away at some point
688 Result.clear();
689 Result.setLookupName(Corrected.getCorrection());
Richard Smith2d670972013-08-17 00:46:16 +0000690 if (FirstDecl)
Kaelyn Uhraina5ee6342012-01-24 19:45:35 +0000691 Result.addDecl(FirstDecl);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000692
693 // If we found an Objective-C instance variable, let
694 // LookupInObjCMethod build the appropriate expression to
695 // reference the ivar.
696 // FIXME: This is a gross hack.
697 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
698 Result.clear();
699 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000700 return E;
Douglas Gregor312eadb2011-04-24 05:37:28 +0000701 }
702
703 goto Corrected;
704 }
705 }
706
707 // We failed to correct; just fall through and let the parser deal with it.
708 Result.suppressDiagnostics();
709 return NameClassification::Unknown();
710
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000711 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000712 // We performed name lookup into the current instantiation, and there were
713 // dependent bases, so we treat this result the same way as any other
714 // dependent nested-name-specifier.
715
716 // C++ [temp.res]p2:
717 // A name used in a template declaration or definition and that is
718 // dependent on a template-parameter is assumed not to name a type
719 // unless the applicable name lookup finds a type name or the name is
720 // qualified by the keyword typename.
721 //
722 // FIXME: If the next token is '<', we might want to ask the parser to
723 // perform some heroics to see if we actually have a
724 // template-argument-list, which would indicate a missing 'template'
725 // keyword here.
Richard Smith05766812012-08-18 00:55:03 +0000726 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
727 NameInfo, IsAddressOfOperand,
728 /*TemplateArgs=*/0);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000729 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000730
731 case LookupResult::Found:
732 case LookupResult::FoundOverloaded:
733 case LookupResult::FoundUnresolvedValue:
734 break;
735
736 case LookupResult::Ambiguous:
David Blaikie4e4d0842012-03-11 07:00:24 +0000737 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor3b887352011-04-27 04:48:22 +0000738 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor312eadb2011-04-24 05:37:28 +0000739 // C++ [temp.local]p3:
740 // A lookup that finds an injected-class-name (10.2) can result in an
741 // ambiguity in certain cases (for example, if it is found in more than
742 // one base class). If all of the injected-class-names that are found
743 // refer to specializations of the same class template, and if the name
744 // is followed by a template-argument-list, the reference refers to the
745 // class template itself and not a specialization thereof, and is not
746 // ambiguous.
747 //
748 // This filtering can make an ambiguous result into an unambiguous one,
749 // so try again after filtering out template names.
750 FilterAcceptableTemplateNames(Result);
751 if (!Result.isAmbiguous()) {
752 IsFilteredTemplateName = true;
753 break;
754 }
755 }
756
757 // Diagnose the ambiguity and return an error.
758 return NameClassification::Error();
759 }
760
David Blaikie4e4d0842012-03-11 07:00:24 +0000761 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor312eadb2011-04-24 05:37:28 +0000762 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
763 // C++ [temp.names]p3:
764 // After name lookup (3.4) finds that a name is a template-name or that
765 // an operator-function-id or a literal- operator-id refers to a set of
766 // overloaded functions any member of which is a function template if
767 // this is followed by a <, the < is always taken as the delimiter of a
768 // template-argument-list and never as the less-than operator.
769 if (!IsFilteredTemplateName)
770 FilterAcceptableTemplateNames(Result);
771
Douglas Gregor3b887352011-04-27 04:48:22 +0000772 if (!Result.empty()) {
773 bool IsFunctionTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000774 bool IsVarTemplate;
Douglas Gregor3b887352011-04-27 04:48:22 +0000775 TemplateName Template;
776 if (Result.end() - Result.begin() > 1) {
777 IsFunctionTemplate = true;
778 Template = Context.getOverloadedTemplateName(Result.begin(),
779 Result.end());
780 } else {
781 TemplateDecl *TD
782 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
783 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000784 IsVarTemplate = isa<VarTemplateDecl>(TD);
785
Douglas Gregor3b887352011-04-27 04:48:22 +0000786 if (SS.isSet() && !SS.isInvalid())
787 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor312eadb2011-04-24 05:37:28 +0000788 /*TemplateKeyword=*/false,
Douglas Gregor3b887352011-04-27 04:48:22 +0000789 TD);
790 else
791 Template = TemplateName(TD);
792 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000793
Douglas Gregor3b887352011-04-27 04:48:22 +0000794 if (IsFunctionTemplate) {
795 // Function templates always go through overload resolution, at which
796 // point we'll perform the various checks (e.g., accessibility) we need
797 // to based on which function we selected.
798 Result.suppressDiagnostics();
799
800 return NameClassification::FunctionTemplate(Template);
801 }
Larisse Voufoef4579c2013-08-06 01:03:05 +0000802
803 return IsVarTemplate ? NameClassification::VarTemplate(Template)
804 : NameClassification::TypeTemplate(Template);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000805 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000806 }
Richard Smith05766812012-08-18 00:55:03 +0000807
Douglas Gregor3b887352011-04-27 04:48:22 +0000808 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor312eadb2011-04-24 05:37:28 +0000809 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
810 DiagnoseUseOfDecl(Type, NameLoc);
811 QualType T = Context.getTypeDeclType(Type);
Richard Smith05766812012-08-18 00:55:03 +0000812 if (SS.isNotEmpty())
813 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000814 return ParsedType::make(T);
Douglas Gregor312eadb2011-04-24 05:37:28 +0000815 }
Richard Smith05766812012-08-18 00:55:03 +0000816
Douglas Gregor312eadb2011-04-24 05:37:28 +0000817 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
818 if (!Class) {
819 // FIXME: It's unfortunate that we don't have a Type node for handling this.
820 if (ObjCCompatibleAliasDecl *Alias
821 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
822 Class = Alias->getClassInterface();
823 }
824
825 if (Class) {
826 DiagnoseUseOfDecl(Class, NameLoc);
827
828 if (NextToken.is(tok::period)) {
829 // Interface. <something> is parsed as a property reference expression.
830 // Just return "unknown" as a fall-through for now.
831 Result.suppressDiagnostics();
832 return NameClassification::Unknown();
833 }
834
835 QualType T = Context.getObjCInterfaceType(Class);
836 return ParsedType::make(T);
837 }
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000838
Richard Smith05766812012-08-18 00:55:03 +0000839 // We can have a type template here if we're classifying a template argument.
840 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
841 return NameClassification::TypeTemplate(
842 TemplateName(cast<TemplateDecl>(FirstDecl)));
843
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000844 // Check for a tag type hidden by a non-type decl in a few cases where it
845 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidis99e9fe02013-05-07 19:54:28 +0000846 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
847 if ((NextToken.is(tok::identifier) ||
848 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
849 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
850 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
851 DiagnoseUseOfDecl(Type, NameLoc);
852 QualType T = Context.getTypeDeclType(Type);
853 if (SS.isNotEmpty())
854 return buildNestedType(*this, SS, T, NameLoc);
855 return ParsedType::make(T);
Kaelyn Uhrain12f32972012-05-02 00:11:40 +0000856 }
Douglas Gregor312eadb2011-04-24 05:37:28 +0000857
Richard Smith05766812012-08-18 00:55:03 +0000858 if (FirstDecl->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000859 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor3b887352011-04-27 04:48:22 +0000860
Douglas Gregor312eadb2011-04-24 05:37:28 +0000861 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
862 return BuildDeclarationNameExpr(SS, Result, ADL);
863}
864
John McCall88232aa2009-08-18 00:00:49 +0000865// Determines the context to return to after temporarily entering a
866// context. This depends in an unnecessarily complicated way on the
867// exact ordering of callbacks from the parser.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000868DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000869
John McCall88232aa2009-08-18 00:00:49 +0000870 // Functions defined inline within classes aren't parsed until we've
871 // finished parsing the top-level class, so the top-level class is
872 // the context we'll need to return to.
873 if (isa<FunctionDecl>(DC)) {
874 DC = DC->getLexicalParent();
875
876 // A function not defined within a class will always return to its
877 // lexical context.
878 if (!isa<CXXRecordDecl>(DC))
879 return DC;
880
881 // A C++ inline method/friend is parsed *after* the topmost class
882 // it was declared in is fully parsed ("complete"); the topmost
883 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000884 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000885 DC = RD;
886
887 // Return the declaration context of the topmost class the inline method is
888 // declared in.
889 return DC;
890 }
891
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000892 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000893}
894
Douglas Gregor44b43212008-12-11 16:49:14 +0000895void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000896 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000897 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000898 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000899 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000900}
901
Chris Lattnerb048c982008-04-06 04:47:34 +0000902void Sema::PopDeclContext() {
903 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000904
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000905 CurContext = getContainingDC(CurContext);
John McCallacb70392010-07-23 22:45:07 +0000906 assert(CurContext && "Popped translation unit!");
Chris Lattner0ed844b2008-04-04 06:12:32 +0000907}
908
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000909/// EnterDeclaratorContext - Used when we must lookup names in the context
910/// of a declarator's nested name specifier.
John McCall7a1dc562009-12-19 10:49:29 +0000911///
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000912void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall7a1dc562009-12-19 10:49:29 +0000913 // C++0x [basic.lookup.unqual]p13:
914 // A name used in the definition of a static data member of class
915 // X (after the qualified-id of the static member) is looked up as
916 // if the name was used in a member function of X.
917 // C++0x [basic.lookup.unqual]p14:
918 // If a variable member of a namespace is defined outside of the
919 // scope of its namespace then any name used in the definition of
920 // the variable member (after the declarator-id) is looked up as
921 // if the definition of the variable member occurred in its
922 // namespace.
923 // Both of these imply that we should push a scope whose context
924 // is the semantic context of the declaration. We can't use
925 // PushDeclContext here because that context is not necessarily
926 // lexically contained in the current context. Fortunately,
927 // the containing scope should have the appropriate information.
928
929 assert(!S->getEntity() && "scope already has entity");
930
931#ifndef NDEBUG
932 Scope *Ancestor = S->getParent();
933 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
934 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
935#endif
936
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000937 CurContext = DC;
John McCall7a1dc562009-12-19 10:49:29 +0000938 S->setEntity(DC);
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000939}
940
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000941void Sema::ExitDeclaratorContext(Scope *S) {
John McCall7a1dc562009-12-19 10:49:29 +0000942 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000943
John McCall7a1dc562009-12-19 10:49:29 +0000944 // Switch back to the lexical context. The safety of this is
945 // enforced by an assert in EnterDeclaratorContext.
946 Scope *Ancestor = S->getParent();
947 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekf0d58612013-10-08 17:08:03 +0000948 CurContext = Ancestor->getEntity();
John McCall7a1dc562009-12-19 10:49:29 +0000949
950 // We don't need to do anything with the scope, which is going to
951 // disappear.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000952}
953
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000954
955void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
956 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
957 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
958 // We assume that the caller has already called
959 // ActOnReenterTemplateScope
960 FD = TFD->getTemplatedDecl();
961 }
962 if (!FD)
963 return;
964
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000965 // Same implementation as PushDeclContext, but enters the context
966 // from the lexical parent, rather than the top-level class.
967 assert(CurContext == FD->getLexicalParent() &&
968 "The next DeclContext should be lexically contained in the current one.");
969 CurContext = FD;
970 S->setEntity(CurContext);
971
Caitlin Sadowskied9d84a2011-09-08 17:42:31 +0000972 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
973 ParmVarDecl *Param = FD->getParamDecl(P);
974 // If the parameter has an identifier, then add it to the scope
975 if (Param->getIdentifier()) {
976 S->AddDecl(Param);
977 IdResolver.AddDecl(Param);
978 }
979 }
980}
981
982
DeLesley Hutchinscf2fa2f2012-04-06 15:10:17 +0000983void Sema::ActOnExitFunctionContext() {
984 // Same implementation as PopDeclContext, but returns to the lexical parent,
985 // rather than the top-level class.
986 assert(CurContext && "DeclContext imbalance!");
987 CurContext = CurContext->getLexicalParent();
988 assert(CurContext && "Popped translation unit!");
989}
990
991
Douglas Gregorf9201e02009-02-11 23:02:49 +0000992/// \brief Determine whether we allow overloading of the function
993/// PrevDecl with another declaration.
994///
995/// This routine determines whether overloading is possible, not
996/// whether some new function is actually an overload. It will return
997/// true in C++ (where we can always provide overloads) or, as an
998/// extension, in C when the previous function is already an
999/// overloaded function declaration or has the "overloadable"
1000/// attribute.
John McCall68263142009-11-18 22:49:29 +00001001static bool AllowOverloadingOfFunction(LookupResult &Previous,
1002 ASTContext &Context) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001003 if (Context.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001004 return true;
1005
John McCall68263142009-11-18 22:49:29 +00001006 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001007 return true;
1008
John McCall68263142009-11-18 22:49:29 +00001009 return (Previous.getResultKind() == LookupResult::Found
1010 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregorf9201e02009-02-11 23:02:49 +00001011}
1012
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001013/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +00001014void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +00001015 // Move up the scope chain until we find the nearest enclosing
1016 // non-transparent context. The declaration will be introduced into this
1017 // scope.
Ted Kremenekf0d58612013-10-08 17:08:03 +00001018 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor074149e2009-01-05 19:45:36 +00001019 S = S->getParent();
1020
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001021 // Add scoped declarations into their context, so that they can be
1022 // found later. Declarations without a context won't be inserted
1023 // into any context.
John McCallab88d972009-08-31 22:39:49 +00001024 if (AddToContext)
1025 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001026
Richard Smitha41c97a2013-09-20 01:15:31 +00001027 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1028 // are function-local declarations.
1029 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregor6d0468b2011-10-09 22:57:49 +00001030 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smitha41c97a2013-09-20 01:15:31 +00001031 D->getLexicalDeclContext()->getRedeclContext()) &&
1032 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruth8761d682010-02-21 07:08:09 +00001033 return;
1034
1035 // Template instantiations should also not be pushed into scope.
1036 if (isa<FunctionDecl>(D) &&
1037 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregord04b1be2009-09-28 18:41:37 +00001038 return;
1039
John McCallf36e02d2009-10-09 21:13:30 +00001040 // If this replaces anything in the current scope,
1041 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1042 IEnd = IdResolver.end();
1043 for (; I != IEnd; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001044 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1045 S->RemoveDecl(*I);
John McCallf36e02d2009-10-09 21:13:30 +00001046 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001047
John McCallf36e02d2009-10-09 21:13:30 +00001048 // Should only need to replace one decl.
1049 break;
Douglas Gregor516ff432009-04-24 02:57:34 +00001050 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001051 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001052
John McCalld226f652010-08-21 09:40:31 +00001053 S->AddDecl(D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001054
1055 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1056 // Implicitly-generated labels may end up getting generated in an order that
1057 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1058 // the label at the appropriate place in the identifier chain.
1059 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregor1d2de762011-03-24 14:35:16 +00001060 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor250e7a72011-03-16 16:39:03 +00001061 if (IDC == CurContext) {
1062 if (!S->isDeclScope(*I))
1063 continue;
1064 } else if (IDC->Encloses(CurContext))
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001065 break;
1066 }
1067
Douglas Gregor250e7a72011-03-16 16:39:03 +00001068 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor7cbc5582011-03-14 21:19:51 +00001069 } else {
1070 IdResolver.AddDecl(D);
1071 }
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001072}
1073
Douglas Gregoreee242f2011-10-27 09:33:13 +00001074void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1075 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1076 TUScope->AddDecl(D);
1077}
1078
Richard Smithdd9459f2013-08-13 18:18:50 +00001079bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001080 bool ExplicitInstantiationOrSpecialization) {
Nico Weber355a1662012-12-17 03:51:09 +00001081 return IdResolver.isDeclInScope(D, Ctx, S,
Douglas Gregorcc209452011-03-07 16:54:27 +00001082 ExplicitInstantiationOrSpecialization);
Douglas Gregor2531c2d2009-09-28 00:47:05 +00001083}
1084
John McCall5f1e0942010-08-24 08:50:51 +00001085Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1086 DeclContext *TargetDC = DC->getPrimaryContext();
1087 do {
Ted Kremenekf0d58612013-10-08 17:08:03 +00001088 if (DeclContext *ScopeDC = S->getEntity())
John McCall5f1e0942010-08-24 08:50:51 +00001089 if (ScopeDC->getPrimaryContext() == TargetDC)
1090 return S;
1091 } while ((S = S->getParent()));
1092
1093 return 0;
1094}
1095
John McCall68263142009-11-18 22:49:29 +00001096static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1097 DeclContext*,
1098 ASTContext&);
1099
1100/// Filters out lookup results that don't fall within the given scope
1101/// as determined by isDeclInScope.
Richard Smith3e4c6c42011-05-05 21:57:07 +00001102void Sema::FilterLookupForScope(LookupResult &R,
1103 DeclContext *Ctx, Scope *S,
1104 bool ConsiderLinkage,
1105 bool ExplicitInstantiationOrSpecialization) {
John McCall68263142009-11-18 22:49:29 +00001106 LookupResult::Filter F = R.makeFilter();
1107 while (F.hasNext()) {
1108 NamedDecl *D = F.next();
1109
Richard Smith3e4c6c42011-05-05 21:57:07 +00001110 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall68263142009-11-18 22:49:29 +00001111 continue;
1112
1113 if (ConsiderLinkage &&
Richard Smith3e4c6c42011-05-05 21:57:07 +00001114 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall68263142009-11-18 22:49:29 +00001115 continue;
1116
1117 F.erase();
1118 }
1119
1120 F.done();
1121}
1122
1123static bool isUsingDecl(NamedDecl *D) {
1124 return isa<UsingShadowDecl>(D) ||
1125 isa<UnresolvedUsingTypenameDecl>(D) ||
1126 isa<UnresolvedUsingValueDecl>(D);
1127}
1128
1129/// Removes using shadow declarations from the lookup results.
1130static void RemoveUsingDecls(LookupResult &R) {
1131 LookupResult::Filter F = R.makeFilter();
1132 while (F.hasNext())
1133 if (isUsingDecl(F.next()))
1134 F.erase();
1135
1136 F.done();
1137}
1138
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001139/// \brief Check for this common pattern:
1140/// @code
1141/// class S {
1142/// S(const S&); // DO NOT IMPLEMENT
1143/// void operator=(const S&); // DO NOT IMPLEMENT
1144/// };
1145/// @endcode
1146static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1147 // FIXME: Should check for private access too but access is set after we get
1148 // the decl here.
Sean Hunt10620eb2011-05-06 20:44:56 +00001149 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001150 return false;
1151
1152 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1153 return CD->isCopyConstructor();
Douglas Gregor27c08ab2010-09-27 22:06:20 +00001154 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1155 return Method->isCopyAssignmentOperator();
1156 return false;
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001157}
1158
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001159// We need this to handle
1160//
1161// typedef struct {
1162// void *foo() { return 0; }
1163// } A;
1164//
1165// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1166// for example. If 'A', foo will have external linkage. If we have '*A',
1167// foo will have no linkage. Since we can't know untill we get to the end
1168// of the typedef, this function finds out if D might have non external linkage.
1169// Callers should verify at the end of the TU if it D has external linkage or
1170// not.
1171bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1172 const DeclContext *DC = D->getDeclContext();
1173 while (!DC->isTranslationUnit()) {
1174 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1175 if (!RD->hasNameForLinkage())
1176 return true;
1177 }
1178 DC = DC->getParent();
1179 }
1180
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001181 return !D->isExternallyVisible();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001182}
1183
Eli Friedman39bd3712013-09-10 03:05:56 +00001184// FIXME: This needs to be refactored; some other isInMainFile users want
1185// these semantics.
1186static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1187 if (S.TUKind != TU_Complete)
1188 return false;
1189 return S.SourceMgr.isInMainFile(Loc);
1190}
1191
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001192bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1193 assert(D);
Argyrios Kyrtzidisf6d1d432010-08-13 18:42:29 +00001194
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001195 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1196 return false;
1197
1198 // Ignore class templates.
Chandler Carruthef9d09c2011-01-03 19:27:19 +00001199 if (D->getDeclContext()->isDependentContext() ||
1200 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001201 return false;
1202
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001203 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001204 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1205 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001206
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001207 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1208 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1209 return false;
1210 } else {
Eli Friedman39bd3712013-09-10 03:05:56 +00001211 // 'static inline' functions are defined in headers; don't warn.
1212 if (FD->isInlineSpecified() &&
1213 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +00001214 return false;
1215 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001216
Sean Hunt10620eb2011-05-06 20:44:56 +00001217 if (FD->doesThisDeclarationHaveABody() &&
John McCall82b96592010-10-27 01:41:35 +00001218 Context.DeclMustBeEmitted(FD))
1219 return false;
John McCall82b96592010-10-27 01:41:35 +00001220 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman39bd3712013-09-10 03:05:56 +00001221 // Constants and utility variables are defined in headers with internal
1222 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1223 // like "inline".)
1224 if (!isMainFileLoc(*this, VD->getLocation()))
1225 return false;
1226
Eli Friedman39bd3712013-09-10 03:05:56 +00001227 if (Context.DeclMustBeEmitted(VD))
John McCall82b96592010-10-27 01:41:35 +00001228 return false;
1229
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001230 if (VD->isStaticDataMember() &&
1231 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1232 return false;
John McCall82b96592010-10-27 01:41:35 +00001233 } else {
1234 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001235 }
1236
John McCall82b96592010-10-27 01:41:35 +00001237 // Only warn for unused decls internal to the translation unit.
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001238 return mightHaveNonExternalLinkage(D);
John McCall82b96592010-10-27 01:41:35 +00001239}
1240
1241void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001242 if (!D)
1243 return;
1244
1245 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001246 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001247 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1248 return; // First should already be in the vector.
1249 }
1250
1251 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001252 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001253 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1254 return; // First should already be in the vector.
1255 }
1256
David Blaikie7f7c42b2012-05-26 05:35:39 +00001257 if (ShouldWarnIfUnusedFileScopedDecl(D))
1258 UnusedFileScopedDecls.push_back(D);
1259}
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00001260
Anders Carlsson99a000e2009-11-07 07:18:14 +00001261static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +00001262 if (D->isInvalidDecl())
1263 return false;
1264
Eli Friedmandd9d6452012-01-13 23:41:25 +00001265 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001266 return false;
John McCall86ff3082010-02-04 22:26:26 +00001267
Chris Lattner57ad3782011-02-17 20:34:02 +00001268 if (isa<LabelDecl>(D))
1269 return true;
1270
John McCall86ff3082010-02-04 22:26:26 +00001271 // White-list anything that isn't a local variable.
1272 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1273 !D->getDeclContext()->isFunctionOrMethod())
1274 return false;
1275
1276 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001277 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +00001278
1279 // White-list anything with an __attribute__((unused)) type.
1280 QualType Ty = VD->getType();
1281
1282 // Only look at the outermost level of typedef.
Douglas Gregor2c8e81e2012-09-14 05:10:40 +00001283 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallaec58602010-03-31 02:47:45 +00001284 if (TT->getDecl()->hasAttr<UnusedAttr>())
1285 return false;
1286 }
1287
Douglas Gregor5764f612010-05-08 23:05:03 +00001288 // If we failed to complete the type for some reason, or if the type is
1289 // dependent, don't diagnose the variable.
1290 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +00001291 return false;
1292
John McCallaec58602010-03-31 02:47:45 +00001293 if (const TagType *TT = Ty->getAs<TagType>()) {
1294 const TagDecl *Tag = TT->getDecl();
1295 if (Tag->hasAttr<UnusedAttr>())
1296 return false;
1297
1298 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001299 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf7613d52009-11-07 07:26:56 +00001300 return false;
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001301
1302 if (const Expr *Init = VD->getInit()) {
David Blaikie39e17762012-10-24 21:29:06 +00001303 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1304 Init = Cleanups->getSubExpr();
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001305 const CXXConstructExpr *Construct =
1306 dyn_cast<CXXConstructExpr>(Init);
1307 if (Construct && !Construct->isElidable()) {
1308 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunak1d3ce652013-07-20 15:05:36 +00001309 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola1a5d3552012-01-06 04:54:01 +00001310 return false;
1311 }
1312 }
Anders Carlssonf7613d52009-11-07 07:26:56 +00001313 }
1314 }
John McCallaec58602010-03-31 02:47:45 +00001315
1316 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +00001317 }
1318
John McCall86ff3082010-02-04 22:26:26 +00001319 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +00001320}
1321
Anna Zaksd5612a22011-07-28 20:52:06 +00001322static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1323 FixItHint &Hint) {
1324 if (isa<LabelDecl>(D)) {
1325 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001326 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaksd5612a22011-07-28 20:52:06 +00001327 if (AfterColon.isInvalid())
1328 return;
1329 Hint = FixItHint::CreateRemoval(CharSourceRange::
1330 getCharRange(D->getLocStart(), AfterColon));
1331 }
1332 return;
1333}
1334
Chris Lattner337e5502011-02-18 01:27:55 +00001335/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1336/// unless they are marked attr(unused).
Douglas Gregor5764f612010-05-08 23:05:03 +00001337void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaksd5612a22011-07-28 20:52:06 +00001338 FixItHint Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001339 if (!ShouldDiagnoseUnusedDecl(D))
1340 return;
1341
Anna Zaksd5612a22011-07-28 20:52:06 +00001342 GenerateFixForUnusedDecl(D, Context, Hint);
1343
Chris Lattner57ad3782011-02-17 20:34:02 +00001344 unsigned DiagID;
Douglas Gregor5764f612010-05-08 23:05:03 +00001345 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattner57ad3782011-02-17 20:34:02 +00001346 DiagID = diag::warn_unused_exception_param;
1347 else if (isa<LabelDecl>(D))
1348 DiagID = diag::warn_unused_label;
Douglas Gregor5764f612010-05-08 23:05:03 +00001349 else
Chris Lattner57ad3782011-02-17 20:34:02 +00001350 DiagID = diag::warn_unused_variable;
1351
Anna Zaksd5612a22011-07-28 20:52:06 +00001352 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor5764f612010-05-08 23:05:03 +00001353}
1354
Chris Lattner337e5502011-02-18 01:27:55 +00001355static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1356 // Verify that we have no forward references left. If so, there was a goto
1357 // or address of a label taken, but no definition of it. Label fwd
1358 // definitions are indicated with a null substmt.
1359 if (L->getStmt() == 0)
1360 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1361}
1362
Steve Naroffb216c882007-10-09 22:01:59 +00001363void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +00001364 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +00001365 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001366 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001367
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1369 I != E; ++I) {
John McCalld226f652010-08-21 09:40:31 +00001370 Decl *TmpD = (*I);
Steve Naroffc752d042007-09-13 18:10:37 +00001371 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001372
Douglas Gregor44b43212008-12-11 16:49:14 +00001373 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1374 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +00001375
Douglas Gregor44b43212008-12-11 16:49:14 +00001376 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +00001377
Douglas Gregorb5352cf2009-10-08 21:35:42 +00001378 // Diagnose unused variables in this scope.
Matt Beaumont-Gay59d8ccb2013-03-28 21:46:45 +00001379 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor5764f612010-05-08 23:05:03 +00001380 DiagnoseUnusedDecl(D);
1381
Chris Lattner337e5502011-02-18 01:27:55 +00001382 // If this was a forward reference to a label, verify it was defined.
1383 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1384 CheckPoppedLabel(LD, *this);
1385
Douglas Gregor44b43212008-12-11 16:49:14 +00001386 // Remove this name from our lexical scope.
1387 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 }
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00001389 DiagnoseUnusedBackingIvarInAccessor(S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001390}
1391
James Molloy16f1f712012-02-29 10:24:19 +00001392void Sema::ActOnStartFunctionDeclarator() {
1393 ++InFunctionDeclarator;
1394}
1395
1396void Sema::ActOnEndFunctionDeclarator() {
1397 assert(InFunctionDeclarator);
1398 --InFunctionDeclarator;
1399}
1400
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001401/// \brief Look for an Objective-C class in the translation unit.
1402///
1403/// \param Id The name of the Objective-C class we're looking for. If
1404/// typo-correction fixes this name, the Id will be updated
1405/// to the fixed name.
1406///
1407/// \param IdLoc The location of the name in the translation unit.
1408///
James Dennett16ae9de2012-06-22 10:16:05 +00001409/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001410/// if there is no class with the given name.
1411///
1412/// \returns The declaration of the named Objective-C class, or NULL if the
1413/// class could not be found.
1414ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1415 SourceLocation IdLoc,
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001416 bool DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001417 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1418 // creation from this context.
1419 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1420
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001421 if (!IDecl && DoTypoCorrection) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001422 // Perform typo correction at the given location, but only if we
1423 // find an Objective-C class name.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001424 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1425 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1426 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001427 Validator)) {
Richard Smith2d670972013-08-17 00:46:16 +00001428 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00001429 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001430 Id = IDecl->getIdentifier();
1431 }
1432 }
Fariborz Jahanian3306f962012-01-12 00:18:35 +00001433 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1434 // This routine must always return a class definition, if any.
1435 if (Def && Def->getDefinition())
1436 Def = Def->getDefinition();
1437 return Def;
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001438}
1439
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001440/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1441/// from S, where a non-field would be declared. This routine copes
1442/// with the difference between C and C++ scoping rules in structs and
1443/// unions. For example, the following code is well-formed in C but
1444/// ill-formed in C++:
1445/// @code
1446/// struct S6 {
1447/// enum { BAR } e;
1448/// };
Mike Stump1eb44332009-09-09 15:08:12 +00001449///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001450/// void test_S6() {
1451/// struct S6 a;
1452/// a.e = BAR;
1453/// }
1454/// @endcode
1455/// For the declaration of BAR, this routine will return a different
1456/// scope. The scope S will be the scope of the unnamed enumeration
1457/// within S6. In C++, this routine will return the scope associated
1458/// with S6, because the enumeration's scope is a transparent
1459/// context but structures can contain non-field names. In C, this
1460/// routine will return the translation unit scope, since the
1461/// enumeration's scope is a transparent context and structures cannot
1462/// contain non-field names.
1463Scope *Sema::getNonFieldDeclScope(Scope *S) {
1464 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +00001465 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001466 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00001467 S = S->getParent();
1468 return S;
1469}
1470
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001471/// \brief Looks up the declaration of "struct objc_super" and
1472/// saves it for later use in building builtin declaration of
1473/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1474/// pre-existing declaration exists no action takes place.
1475static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1476 IdentifierInfo *II) {
1477 if (!II->isStr("objc_msgSendSuper"))
1478 return;
1479 ASTContext &Context = ThisSema.Context;
1480
1481 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1482 SourceLocation(), Sema::LookupTagName);
1483 ThisSema.LookupName(Result, S);
1484 if (Result.getResultKind() == LookupResult::Found)
1485 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1486 Context.setObjCSuperType(Context.getTagDeclType(TD));
1487}
1488
Douglas Gregor3e41d602009-02-13 23:20:09 +00001489/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1490/// file scope. lazily create a decl for it. ForRedeclaration is true
1491/// if we're creating this built-in in anticipation of redeclaring the
1492/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001493NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001494 Scope *S, bool ForRedeclaration,
1495 SourceLocation Loc) {
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001496 LookupPredefedObjCSuperType(*this, S, II);
1497
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 Builtin::ID BID = (Builtin::ID)bid;
1499
Chris Lattner86df27b2009-06-14 00:45:47 +00001500 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001501 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001502 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +00001503 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001504 // Okay
1505 break;
1506
Mike Stumpf711c412009-07-28 23:57:15 +00001507 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001508 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001509 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001510 << Context.BuiltinInfo.GetName(BID);
1511 return 0;
Mike Stump782fa302009-07-28 02:25:19 +00001512
Mike Stumpf711c412009-07-28 23:57:15 +00001513 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +00001514 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +00001515 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stump782fa302009-07-28 02:25:19 +00001516 << Context.BuiltinInfo.GetName(BID);
1517 return 0;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00001518
1519 case ASTContext::GE_Missing_ucontext:
1520 if (ForRedeclaration)
1521 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1522 << Context.BuiltinInfo.GetName(BID);
1523 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001524 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00001525
1526 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1527 Diag(Loc, diag::ext_implicit_lib_function_decl)
1528 << Context.BuiltinInfo.GetName(BID)
1529 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +00001530 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001531 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikied6471f72011-09-25 23:23:43 +00001532 != DiagnosticsEngine::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +00001533 Diag(Loc, diag::note_please_include_header)
1534 << Context.BuiltinInfo.getHeaderName(BID)
1535 << Context.BuiltinInfo.GetName(BID);
1536 }
1537
Warren Hunt2d023ec2013-11-01 23:46:51 +00001538 DeclContext *Parent = Context.getTranslationUnitDecl();
1539 if (getLangOpts().CPlusPlus) {
1540 LinkageSpecDecl *CLinkageDecl =
1541 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1542 LinkageSpecDecl::lang_c, false);
1543 Parent->addDecl(CLinkageDecl);
1544 Parent = CLinkageDecl;
1545 }
1546
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +00001547 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt2d023ec2013-11-01 23:46:51 +00001548 Parent,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001549 Loc, Loc, II, R, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001550 SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001551 false,
Douglas Gregor2224f842009-02-25 16:33:18 +00001552 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001553 New->setImplicit();
1554
Chris Lattner95e2c712008-05-05 22:18:14 +00001555 // Create Decl objects for each parameter, adding them to the
1556 // FunctionDecl.
John McCallf4c73712011-01-19 06:33:43 +00001557 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001558 SmallVector<ParmVarDecl*, 16> Params;
John McCallfb44de92011-05-01 22:35:37 +00001559 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1560 ParmVarDecl *parm =
1561 ParmVarDecl::Create(Context, New, SourceLocation(),
1562 SourceLocation(), 0,
1563 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001564 SC_None, 0);
John McCallfb44de92011-05-01 22:35:37 +00001565 parm->setScopeInfo(0, i);
1566 Params.push_back(parm);
1567 }
David Blaikie4278c652011-09-21 18:16:56 +00001568 New->setParams(Params);
Chris Lattner95e2c712008-05-05 22:18:14 +00001569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
1571 AddKnownFunctionAttributes(New);
Warren Hunt2d023ec2013-11-01 23:46:51 +00001572 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Chris Lattner7f925cc2008-04-11 07:00:53 +00001574 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001575 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1576 // relate Scopes to DeclContexts, and probably eliminate CurContext
1577 // entirely, but we're not there yet.
1578 DeclContext *SavedContext = CurContext;
Warren Hunt2d023ec2013-11-01 23:46:51 +00001579 CurContext = Parent;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001580 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00001581 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 return New;
1583}
1584
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001585/// \brief Filter out any previous declarations that the given declaration
1586/// should not consider because they are not permitted to conflict, e.g.,
1587/// because they come from hidden sub-modules and do not refer to the same
1588/// entity.
1589static void filterNonConflictingPreviousDecls(ASTContext &context,
1590 NamedDecl *decl,
1591 LookupResult &previous){
1592 // This is only interesting when modules are enabled.
1593 if (!context.getLangOpts().Modules)
1594 return;
1595
1596 // Empty sets are uninteresting.
1597 if (previous.empty())
1598 return;
1599
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001600 LookupResult::Filter filter = previous.makeFilter();
1601 while (filter.hasNext()) {
1602 NamedDecl *old = filter.next();
1603
1604 // Non-hidden declarations are never ignored.
1605 if (!old->isHidden())
1606 continue;
1607
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001608 if (!old->isExternallyVisible())
Douglas Gregor7dc80e12013-01-09 00:47:56 +00001609 filter.erase();
1610 }
1611
1612 filter.done();
1613}
1614
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001615bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1616 QualType OldType;
1617 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1618 OldType = OldTypedef->getUnderlyingType();
1619 else
1620 OldType = Context.getTypeDeclType(Old);
1621 QualType NewType = New->getUnderlyingType();
1622
Douglas Gregorec3bd722012-01-11 22:33:48 +00001623 if (NewType->isVariablyModifiedType()) {
1624 // Must not redefine a typedef with a variably-modified type.
1625 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1626 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1627 << Kind << NewType;
1628 if (Old->getLocation().isValid())
1629 Diag(Old->getLocation(), diag::note_previous_definition);
1630 New->setInvalidDecl();
1631 return true;
1632 }
1633
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001634 if (OldType != NewType &&
1635 !OldType->isDependentType() &&
1636 !NewType->isDependentType() &&
Douglas Gregorec3bd722012-01-11 22:33:48 +00001637 !Context.hasSameType(OldType, NewType)) {
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001638 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1639 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1640 << Kind << NewType << OldType;
1641 if (Old->getLocation().isValid())
1642 Diag(Old->getLocation(), diag::note_previous_definition);
1643 New->setInvalidDecl();
1644 return true;
1645 }
1646 return false;
1647}
1648
Richard Smith162e1c12011-04-15 14:24:37 +00001649/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregorcda9c672009-02-16 17:45:42 +00001650/// same name and scope as a previous declaration 'Old'. Figure out
1651/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +00001652/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001653///
Richard Smith162e1c12011-04-15 14:24:37 +00001654void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall68263142009-11-18 22:49:29 +00001655 // If the new decl is known invalid already, don't bother doing any
1656 // merging checks.
1657 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Steve Naroff2b255c42008-09-09 14:32:20 +00001659 // Allow multiple definitions for ObjC built-in typedefs.
1660 // FIXME: Verify the underlying types are equivalent!
David Blaikie4e4d0842012-03-11 07:00:24 +00001661 if (getLangOpts().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +00001662 const IdentifierInfo *TypeID = New->getIdentifier();
1663 switch (TypeID->getLength()) {
1664 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +00001665 case 2:
Fariborz Jahanian0cd00be2012-05-14 22:48:56 +00001666 {
1667 if (!TypeID->isStr("id"))
1668 break;
1669 QualType T = New->getUnderlyingType();
1670 if (!T->isPointerType())
1671 break;
1672 if (!T->isVoidPointerType()) {
1673 QualType PT = T->getAs<PointerType>()->getPointeeType();
1674 if (!PT->isStructureType())
1675 break;
1676 }
1677 Context.setObjCIdRedefinitionType(T);
1678 // Install the built-in type for 'id', ignoring the current definition.
1679 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1680 return;
1681 }
Chris Lattner2bac0f62008-11-20 05:41:43 +00001682 case 5:
1683 if (!TypeID->isStr("Class"))
1684 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001685 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff14108da2009-07-10 23:34:53 +00001686 // Install the built-in type for 'Class', ignoring the current definition.
1687 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001688 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +00001689 case 3:
1690 if (!TypeID->isStr("SEL"))
1691 break;
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001692 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001693 // Install the built-in type for 'SEL', ignoring the current definition.
1694 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +00001695 return;
Steve Naroff2b255c42008-09-09 14:32:20 +00001696 }
1697 // Fall through - the typedef name was not a builtin type.
1698 }
John McCall68263142009-11-18 22:49:29 +00001699
Douglas Gregor66973122009-01-28 17:15:10 +00001700 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +00001701 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1702 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +00001703 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001704 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001705
1706 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001707 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00001708 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +00001709
Chris Lattnereaaebc72009-04-25 08:06:05 +00001710 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 }
Douglas Gregor66973122009-01-28 17:15:10 +00001712
John McCall68263142009-11-18 22:49:29 +00001713 // If the old declaration is invalid, just give up here.
1714 if (Old->isInvalidDecl())
1715 return New->setInvalidDecl();
1716
Chris Lattner99cb9972008-07-25 18:44:27 +00001717 // If the typedef types are not identical, reject them in all languages and
1718 // with any extensions enabled.
Rafael Espindola5df37bd2011-12-26 22:42:47 +00001719 if (isIncompatibleTypedef(Old, New))
1720 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Justin Bogner2dd68de2013-10-08 00:19:09 +00001722 // The types match. Link up the redeclaration chain and merge attributes if
1723 // the old declaration was a typedef.
1724 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001725 New->setPreviousDecl(Typedef);
Justin Bogner2dd68de2013-10-08 00:19:09 +00001726 mergeDeclAttributes(New, Old);
1727 }
Eli Friedman9ec40992013-07-16 02:07:49 +00001728
David Blaikie4e4d0842012-03-11 07:00:24 +00001729 if (getLangOpts().MicrosoftExt)
Chris Lattnereaaebc72009-04-25 08:06:05 +00001730 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +00001731
David Blaikie4e4d0842012-03-11 07:00:24 +00001732 if (getLangOpts().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +00001733 // C++ [dcl.typedef]p2:
1734 // In a given non-class scope, a typedef specifier can be used to
1735 // redefine the name of any type declared in that scope to refer
1736 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +00001737 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +00001738 return;
Douglas Gregor93dda722010-01-11 21:54:40 +00001739
1740 // C++0x [dcl.typedef]p4:
1741 // In a given class scope, a typedef specifier can be used to redefine
1742 // any class-name declared in that scope that is not also a typedef-name
1743 // to refer to the type to which it already refers.
1744 //
1745 // This wording came in via DR424, which was a correction to the
1746 // wording in DR56, which accidentally banned code like:
1747 //
1748 // struct S {
1749 // typedef struct A { } A;
1750 // };
1751 //
1752 // in the C++03 standard. We implement the C++0x semantics, which
1753 // allow the above but disallow
1754 //
1755 // struct S {
1756 // typedef int I;
1757 // typedef int I;
1758 // };
1759 //
1760 // since that was the intent of DR56.
Richard Smith162e1c12011-04-15 14:24:37 +00001761 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +00001762 return;
1763
Chris Lattner32b06752009-04-17 22:04:20 +00001764 Diag(New->getLocation(), diag::err_redefinition)
1765 << New->getDeclName();
1766 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001767 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +00001768 }
Eli Friedman54ecfce2008-06-11 06:20:39 +00001769
Douglas Gregorc0004df2012-01-11 04:25:01 +00001770 // Modules always permit redefinition of typedefs, as does C11.
David Blaikie4e4d0842012-03-11 07:00:24 +00001771 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregorc02d62f2012-01-09 15:36:04 +00001772 return;
1773
Chris Lattner32b06752009-04-17 22:04:20 +00001774 // If we have a redefinition of a typedef in C, emit a warning. This warning
1775 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +00001776 // -Wtypedef-redefinition. If either the original or the redefinition is
1777 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00001778 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +00001779 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1780 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +00001781 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Chris Lattner32b06752009-04-17 22:04:20 +00001783 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1784 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001785 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001786 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001787}
1788
Chris Lattner6b6b5372008-06-26 18:38:35 +00001789/// DeclhasAttr - returns true if decl Declaration already has the target
1790/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00001791static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001792DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola3b294362012-05-06 19:56:25 +00001793 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1794 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1795 // responsible for making sure they are consistent.
1796 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1797 if (AA)
1798 return false;
1799
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001800 // The following thread safety attributes can also be duplicated.
1801 switch (A->getKind()) {
1802 case attr::ExclusiveLocksRequired:
1803 case attr::SharedLocksRequired:
1804 case attr::LocksExcluded:
1805 case attr::ExclusiveLockFunction:
1806 case attr::SharedLockFunction:
1807 case attr::UnlockFunction:
1808 case attr::ExclusiveTrylockFunction:
1809 case attr::SharedTrylockFunction:
1810 case attr::GuardedBy:
1811 case attr::PtGuardedBy:
1812 case attr::AcquiredBefore:
1813 case attr::AcquiredAfter:
1814 return false;
DeLesley Hutchins6c500b12012-10-12 21:49:04 +00001815 default:
1816 ;
DeLesley Hutchins3ce9fae2012-10-12 21:38:12 +00001817 }
1818
Sean Huntcf807c42010-08-18 23:23:40 +00001819 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001820 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Sean Huntcf807c42010-08-18 23:23:40 +00001821 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1822 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001823 if (Ann) {
1824 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1825 return true;
1826 continue;
1827 }
Sean Huntcf807c42010-08-18 23:23:40 +00001828 // FIXME: Don't hardcode this check
1829 if (OA && isa<OwnershipAttr>(*i))
1830 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001831 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001832 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001833
1834 return false;
1835}
1836
Richard Smith671b3212013-02-22 04:55:39 +00001837static bool isAttributeTargetADefinition(Decl *D) {
1838 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1839 return VD->isThisDeclarationADefinition();
1840 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1841 return TD->isCompleteDefinition() || TD->isBeingDefined();
1842 return true;
1843}
1844
1845/// Merge alignment attributes from \p Old to \p New, taking into account the
1846/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1847///
1848/// \return \c true if any attributes were added to \p New.
1849static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1850 // Look for alignas attributes on Old, and pick out whichever attribute
1851 // specifies the strictest alignment requirement.
1852 AlignedAttr *OldAlignasAttr = 0;
1853 AlignedAttr *OldStrictestAlignAttr = 0;
1854 unsigned OldAlign = 0;
1855 for (specific_attr_iterator<AlignedAttr>
1856 I = Old->specific_attr_begin<AlignedAttr>(),
1857 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1858 // FIXME: We have no way of representing inherited dependent alignments
1859 // in a case like:
1860 // template<int A, int B> struct alignas(A) X;
1861 // template<int A, int B> struct alignas(B) X {};
1862 // For now, we just ignore any alignas attributes which are not on the
1863 // definition in such a case.
1864 if (I->isAlignmentDependent())
1865 return false;
1866
1867 if (I->isAlignas())
1868 OldAlignasAttr = *I;
1869
1870 unsigned Align = I->getAlignment(S.Context);
1871 if (Align > OldAlign) {
1872 OldAlign = Align;
1873 OldStrictestAlignAttr = *I;
1874 }
1875 }
1876
1877 // Look for alignas attributes on New.
1878 AlignedAttr *NewAlignasAttr = 0;
1879 unsigned NewAlign = 0;
1880 for (specific_attr_iterator<AlignedAttr>
1881 I = New->specific_attr_begin<AlignedAttr>(),
1882 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1883 if (I->isAlignmentDependent())
1884 return false;
1885
1886 if (I->isAlignas())
1887 NewAlignasAttr = *I;
1888
1889 unsigned Align = I->getAlignment(S.Context);
1890 if (Align > NewAlign)
1891 NewAlign = Align;
1892 }
1893
1894 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1895 // Both declarations have 'alignas' attributes. We require them to match.
1896 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1897 // fall short. (If two declarations both have alignas, they must both match
1898 // every definition, and so must match each other if there is a definition.)
1899
1900 // If either declaration only contains 'alignas(0)' specifiers, then it
1901 // specifies the natural alignment for the type.
1902 if (OldAlign == 0 || NewAlign == 0) {
1903 QualType Ty;
1904 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1905 Ty = VD->getType();
1906 else
1907 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1908
1909 if (OldAlign == 0)
1910 OldAlign = S.Context.getTypeAlign(Ty);
1911 if (NewAlign == 0)
1912 NewAlign = S.Context.getTypeAlign(Ty);
1913 }
1914
1915 if (OldAlign != NewAlign) {
1916 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1917 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1918 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1919 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1920 }
1921 }
1922
1923 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1924 // C++11 [dcl.align]p6:
1925 // if any declaration of an entity has an alignment-specifier,
1926 // every defining declaration of that entity shall specify an
1927 // equivalent alignment.
1928 // C11 6.7.5/7:
1929 // If the definition of an object does not have an alignment
1930 // specifier, any other declaration of that object shall also
1931 // have no alignment specifier.
1932 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1933 << OldAlignasAttr->isC11();
1934 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1935 << OldAlignasAttr->isC11();
1936 }
1937
1938 bool AnyAdded = false;
1939
1940 // Ensure we have an attribute representing the strictest alignment.
1941 if (OldAlign > NewAlign) {
1942 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1943 Clone->setInherited(true);
1944 New->addAttr(Clone);
1945 AnyAdded = true;
1946 }
1947
1948 // Ensure we have an alignas attribute if the old declaration had one.
1949 if (OldAlignasAttr && !NewAlignasAttr &&
1950 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1951 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1952 Clone->setInherited(true);
1953 New->addAttr(Clone);
1954 AnyAdded = true;
1955 }
1956
1957 return AnyAdded;
1958}
1959
1960static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1961 bool Override) {
Rafael Espindola599f1b72012-05-13 03:25:18 +00001962 InheritableAttr *NewAttr = NULL;
Michael Han51d8c522013-01-24 16:46:58 +00001963 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola838dc592013-01-12 06:42:30 +00001964 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001965 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1966 AA->getIntroduced(), AA->getDeprecated(),
1967 AA->getObsoleted(), AA->getUnavailable(),
1968 AA->getMessage(), Override,
John McCalld4c3d662013-02-20 01:54:26 +00001969 AttrSpellingListIndex);
Richard Smith671b3212013-02-22 04:55:39 +00001970 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1971 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1972 AttrSpellingListIndex);
1973 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1974 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1975 AttrSpellingListIndex);
Rafael Espindola838dc592013-01-12 06:42:30 +00001976 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001977 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1978 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001979 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001980 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1981 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001982 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001983 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1984 FA->getFormatIdx(), FA->getFirstArg(),
1985 AttrSpellingListIndex);
Rafael Espindola599f1b72012-05-13 03:25:18 +00001986 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001987 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1988 AttrSpellingListIndex);
1989 else if (isa<AlignedAttr>(Attr))
1990 // AlignedAttrs are handled separately, because we need to handle all
1991 // such attributes on a declaration at the same time.
1992 NewAttr = 0;
Rafael Espindola599f1b72012-05-13 03:25:18 +00001993 else if (!DeclHasAttr(D, Attr))
Richard Smith671b3212013-02-22 04:55:39 +00001994 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindola98ae8342012-05-10 02:50:16 +00001995
Rafael Espindola599f1b72012-05-13 03:25:18 +00001996 if (NewAttr) {
Rafael Espindola98ae8342012-05-10 02:50:16 +00001997 NewAttr->setInherited(true);
1998 D->addAttr(NewAttr);
1999 return true;
2000 }
2001
2002 return false;
2003}
2004
Rafael Espindola4b044c62012-07-15 01:05:36 +00002005static const Decl *getDefinition(const Decl *D) {
2006 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola3f664062012-05-18 01:47:00 +00002007 return TD->getDefinition();
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002008 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2009 const VarDecl *Def = VD->getDefinition();
2010 if (Def)
2011 return Def;
2012 return VD->getActingDefinition();
2013 }
Rafael Espindola4b044c62012-07-15 01:05:36 +00002014 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola3f664062012-05-18 01:47:00 +00002015 const FunctionDecl* Def;
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002016 if (FD->isDefined(Def))
Rafael Espindola3f664062012-05-18 01:47:00 +00002017 return Def;
2018 }
2019 return NULL;
2020}
2021
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002022static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2023 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2024 I != E; ++I) {
2025 Attr *Attribute = *I;
2026 if (Attribute->getKind() == Kind)
2027 return true;
2028 }
2029 return false;
2030}
2031
2032/// checkNewAttributesAfterDef - If we already have a definition, check that
2033/// there are no new attributes in this declaration.
2034static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2035 if (!New->hasAttrs())
2036 return;
2037
2038 const Decl *Def = getDefinition(Old);
2039 if (!Def || Def == New)
2040 return;
2041
2042 AttrVec &NewAttributes = New->getAttrs();
2043 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2044 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002045
2046 if (isa<AliasAttr>(NewAttribute)) {
2047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2048 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2049 else {
2050 VarDecl *VD = cast<VarDecl>(New);
2051 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2052 VarDecl::TentativeDefinition
2053 ? diag::err_alias_after_tentative
2054 : diag::err_redefinition;
2055 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2056 S.Diag(Def->getLocation(), diag::note_previous_definition);
2057 VD->setInvalidDecl();
2058 }
2059 ++I;
2060 continue;
2061 }
2062
2063 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2064 // Tentative definitions are only interesting for the alias check above.
2065 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2066 ++I;
2067 continue;
2068 }
2069 }
2070
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002071 if (hasAttribute(Def, NewAttribute->getKind())) {
2072 ++I;
2073 continue; // regular attr merging will take care of validating this.
2074 }
Richard Smith671b3212013-02-22 04:55:39 +00002075
Richard Smith7586a6e2013-01-30 05:45:05 +00002076 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smith671b3212013-02-22 04:55:39 +00002077 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smith7586a6e2013-01-30 05:45:05 +00002078 ++I;
2079 continue;
Richard Smith671b3212013-02-22 04:55:39 +00002080 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2081 if (AA->isAlignas()) {
2082 // C++11 [dcl.align]p6:
2083 // if any declaration of an entity has an alignment-specifier,
2084 // every defining declaration of that entity shall specify an
2085 // equivalent alignment.
2086 // C11 6.7.5/7:
2087 // If the definition of an object does not have an alignment
2088 // specifier, any other declaration of that object shall also
2089 // have no alignment specifier.
2090 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2091 << AA->isC11();
2092 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2093 << AA->isC11();
2094 NewAttributes.erase(NewAttributes.begin() + I);
2095 --E;
2096 continue;
2097 }
Richard Smith7586a6e2013-01-30 05:45:05 +00002098 }
Richard Smith671b3212013-02-22 04:55:39 +00002099
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002100 S.Diag(NewAttribute->getLocation(),
2101 diag::warn_attribute_precede_definition);
2102 S.Diag(Def->getLocation(), diag::note_previous_definition);
2103 NewAttributes.erase(NewAttributes.begin() + I);
2104 --E;
2105 }
2106}
2107
John McCalleca5d222011-03-02 04:00:57 +00002108/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindola51be6e32013-01-08 22:04:34 +00002109void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002110 AvailabilityMergeKind AMK) {
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002111 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2112 UsedAttr *NewAttr = OldAttr->clone(Context);
2113 NewAttr->setInherited(true);
2114 New->addAttr(NewAttr);
2115 }
2116
Richard Smith3a2b7a12013-01-28 22:42:45 +00002117 if (!Old->hasAttrs() && !New->hasAttrs())
2118 return;
2119
Rafael Espindola3f664062012-05-18 01:47:00 +00002120 // attributes declared post-definition are currently ignored
Rafael Espindolad320ffc2012-07-15 01:33:40 +00002121 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola3f664062012-05-18 01:47:00 +00002122
Douglas Gregor27c6da22012-01-01 20:30:41 +00002123 if (!Old->hasAttrs())
Sean Huntcf807c42010-08-18 23:23:40 +00002124 return;
John McCalleca5d222011-03-02 04:00:57 +00002125
Douglas Gregor27c6da22012-01-01 20:30:41 +00002126 bool foundAny = New->hasAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002127
Sean Huntcf807c42010-08-18 23:23:40 +00002128 // Ensure that any moving of objects within the allocated map is done before
2129 // we process them.
Douglas Gregor27c6da22012-01-01 20:30:41 +00002130 if (!foundAny) New->setAttrs(AttrVec());
John McCalleca5d222011-03-02 04:00:57 +00002131
Peter Collingbournea97d70b2011-01-21 02:08:36 +00002132 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor27c6da22012-01-01 20:30:41 +00002133 i = Old->specific_attr_begin<InheritableAttr>(),
2134 e = Old->specific_attr_end<InheritableAttr>();
2135 i != e; ++i) {
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002136 bool Override = false;
Douglas Gregorc193dd82011-09-23 20:23:42 +00002137 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002138 if (isa<DeprecatedAttr>(*i) ||
2139 isa<UnavailableAttr>(*i) ||
2140 isa<AvailabilityAttr>(*i)) {
2141 switch (AMK) {
2142 case AMK_None:
2143 continue;
John McCall6c2c2502011-07-22 02:45:48 +00002144
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002145 case AMK_Redeclaration:
2146 break;
2147
2148 case AMK_Override:
2149 Override = true;
2150 break;
2151 }
2152 }
2153
Rafael Espindola101e9dc2013-10-25 01:28:12 +00002154 // Already handled.
2155 if (isa<UsedAttr>(*i))
2156 continue;
2157
Richard Smith671b3212013-02-22 04:55:39 +00002158 if (mergeDeclAttribute(*this, New, *i, Override))
John McCalleca5d222011-03-02 04:00:57 +00002159 foundAny = true;
Chris Lattnerddee4232008-03-03 03:28:21 +00002160 }
John McCalleca5d222011-03-02 04:00:57 +00002161
Richard Smith671b3212013-02-22 04:55:39 +00002162 if (mergeAlignedAttrs(*this, New, Old))
2163 foundAny = true;
2164
Douglas Gregor27c6da22012-01-01 20:30:41 +00002165 if (!foundAny) New->dropAttrs();
John McCalleca5d222011-03-02 04:00:57 +00002166}
2167
2168/// mergeParamDeclAttributes - Copy attributes from the old parameter
2169/// to the new one.
2170static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2171 const ParmVarDecl *oldDecl,
Richard Smith3a2b7a12013-01-28 22:42:45 +00002172 Sema &S) {
2173 // C++11 [dcl.attr.depend]p2:
2174 // The first declaration of a function shall specify the
2175 // carries_dependency attribute for its declarator-id if any declaration
2176 // of the function specifies the carries_dependency attribute.
2177 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2178 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2179 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2180 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2181 // Find the first declaration of the parameter.
2182 // FIXME: Should we build redeclaration chains for function parameters?
2183 const FunctionDecl *FirstFD =
Rafael Espindolabc650912013-10-17 15:37:26 +00002184 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smith3a2b7a12013-01-28 22:42:45 +00002185 const ParmVarDecl *FirstVD =
2186 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2187 S.Diag(FirstVD->getLocation(),
2188 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2189 }
2190
John McCalleca5d222011-03-02 04:00:57 +00002191 if (!oldDecl->hasAttrs())
2192 return;
2193
2194 bool foundAny = newDecl->hasAttrs();
2195
2196 // Ensure that any moving of objects within the allocated map is
2197 // done before we process them.
2198 if (!foundAny) newDecl->setAttrs(AttrVec());
2199
2200 for (specific_attr_iterator<InheritableParamAttr>
2201 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2202 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2203 if (!DeclHasAttr(newDecl, *i)) {
Richard Smith3a2b7a12013-01-28 22:42:45 +00002204 InheritableAttr *newAttr =
2205 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCalleca5d222011-03-02 04:00:57 +00002206 newAttr->setInherited(true);
2207 newDecl->addAttr(newAttr);
2208 foundAny = true;
2209 }
2210 }
2211
2212 if (!foundAny) newDecl->dropAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +00002213}
2214
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002215namespace {
2216
Douglas Gregorc8376562009-03-06 22:43:54 +00002217/// Used in MergeFunctionDecl to keep track of function parameters in
2218/// C.
2219struct GNUCompatibleParamWarning {
2220 ParmVarDecl *OldParm;
2221 ParmVarDecl *NewParm;
2222 QualType PromotedType;
2223};
2224
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002225}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002226
2227/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002228Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002229 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Sean Huntf961ea52011-05-10 19:08:14 +00002230 if (Ctor->isDefaultConstructor())
2231 return Sema::CXXDefaultConstructor;
Sean Hunt9ae60d52011-05-26 01:26:05 +00002232
2233 if (Ctor->isCopyConstructor())
2234 return Sema::CXXCopyConstructor;
2235
2236 if (Ctor->isMoveConstructor())
2237 return Sema::CXXMoveConstructor;
Sean Hunt82713172011-05-25 23:16:36 +00002238 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002239 return Sema::CXXDestructor;
Sean Hunt82713172011-05-25 23:16:36 +00002240 } else if (MD->isCopyAssignmentOperator()) {
Sean Huntf961ea52011-05-10 19:08:14 +00002241 return Sema::CXXCopyAssignment;
Sebastian Redl74e611a2011-09-04 18:14:28 +00002242 } else if (MD->isMoveAssignmentOperator()) {
2243 return Sema::CXXMoveAssignment;
Sean Hunt82713172011-05-25 23:16:36 +00002244 }
Sean Huntf961ea52011-05-10 19:08:14 +00002245
Sean Huntf961ea52011-05-10 19:08:14 +00002246 return Sema::CXXInvalid;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002247}
2248
Sebastian Redl515ddd82010-06-09 21:17:41 +00002249/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002250/// only extern inline functions can be redefined, and even then only in
2251/// GNU89 mode.
2252static bool canRedefineFunction(const FunctionDecl *FD,
2253 const LangOptions& LangOpts) {
Eli Friedmaneca3ed72011-06-13 23:56:42 +00002254 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2255 !LangOpts.CPlusPlus &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002256 FD->isInlineSpecified() &&
John McCalld931b082010-08-26 03:08:43 +00002257 FD->getStorageClass() == SC_Extern);
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002258}
2259
Reid Kleckneref072032013-08-27 23:08:25 +00002260const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2261 const AttributedType *AT = T->getAs<AttributedType>();
2262 while (AT && !AT->isCallingConv())
2263 AT = AT->getModifiedType()->getAs<AttributedType>();
2264 return AT;
John McCallfb609142012-08-25 02:00:03 +00002265}
2266
Benjamin Kramera574c892013-02-15 12:30:38 +00002267template <typename T>
2268static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindola950fee22013-02-14 01:18:37 +00002269 const DeclContext *DC = Old->getDeclContext();
2270 if (DC->isRecord())
2271 return false;
2272
2273 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002274 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002275 return true;
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002276 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindola950fee22013-02-14 01:18:37 +00002277 return true;
2278 return false;
2279}
2280
Chris Lattner04421082008-04-08 04:40:51 +00002281/// MergeFunctionDecl - We just parsed a function 'New' from
2282/// declarator D which has the same name and scope as a previous
2283/// declaration 'Old'. Figure out how to resolve this situation,
2284/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002285///
2286/// In C++, New and Old must be declarations that are not
2287/// overloaded. Use IsOverload to determine whether New and Old are
2288/// overloaded, and to select the Old declaration that New should be
2289/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002290///
2291/// Returns true if there was an error, false otherwise.
Richard Smithdd9459f2013-08-13 18:18:50 +00002292bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2293 bool MergeTypeWithOld) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002295 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002296 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00002297 = dyn_cast<FunctionTemplateDecl>(OldD))
2298 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002299 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002300 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002301 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00002302 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCall78037ac2013-04-03 21:19:47 +00002303 if (New->getFriendObjectKind()) {
2304 Diag(New->getLocation(), diag::err_using_decl_friend);
2305 Diag(Shadow->getTargetDecl()->getLocation(),
2306 diag::note_using_decl_target);
2307 Diag(Shadow->getUsingDecl()->getLocation(),
2308 diag::note_using_decl) << 0;
2309 return true;
2310 }
2311
John McCall41ce66f2009-12-10 19:51:03 +00002312 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2313 Diag(Shadow->getTargetDecl()->getLocation(),
2314 diag::note_using_decl_target);
2315 Diag(Shadow->getUsingDecl()->getLocation(),
2316 diag::note_using_decl) << 0;
2317 return true;
2318 }
2319
Chris Lattner5dc266a2008-11-20 06:13:02 +00002320 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00002321 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002322 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00002323 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002324 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002325
David Majnemerbcd06502013-07-07 23:49:50 +00002326 // If the old declaration is invalid, just give up here.
2327 if (Old->isInvalidDecl())
2328 return true;
2329
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002330 // Determine whether the previous declaration was a definition,
2331 // implicit declaration, or a declaration.
2332 diag::kind PrevDiag;
2333 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00002334 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002335 else if (Old->isImplicit())
2336 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002337 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00002338 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Charles Davisf3f8d2a2010-02-18 02:00:42 +00002340 // Don't complain about this if we're in GNU89 mode and the old function
2341 // is an extern inline function.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002342 // Don't complain about specializations. They are not supposed to have
2343 // storage classes.
Douglas Gregor04495c82009-02-24 01:23:02 +00002344 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCalld931b082010-08-26 03:08:43 +00002345 New->getStorageClass() == SC_Static &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00002346 Old->hasExternalFormalLinkage() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002347 !New->getTemplateSpecializationInfo() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002348 !canRedefineFunction(Old, getLangOpts())) {
2349 if (getLangOpts().MicrosoftExt) {
Francois Pichet4bada2e2011-04-22 19:50:06 +00002350 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2351 Diag(Old->getLocation(), PrevDiag);
2352 } else {
2353 Diag(New->getLocation(), diag::err_static_non_static) << New;
2354 Diag(Old->getLocation(), PrevDiag);
2355 return true;
2356 }
Douglas Gregor04495c82009-02-24 01:23:02 +00002357 }
2358
Reid Kleckneref072032013-08-27 23:08:25 +00002359
2360 // If a function is first declared with a calling convention, but is later
2361 // declared or defined without one, all following decls assume the calling
2362 // convention of the first.
John McCallf82b4e82010-02-04 05:44:44 +00002363 //
John McCallfb609142012-08-25 02:00:03 +00002364 // It's OK if a function is first declared without a calling convention,
2365 // but is later declared or defined with the default calling convention.
2366 //
Reid Kleckneref072032013-08-27 23:08:25 +00002367 // To test if either decl has an explicit calling convention, we look for
2368 // AttributedType sugar nodes on the type as written. If they are missing or
2369 // were canonicalized away, we assume the calling convention was implicit.
John McCallf82b4e82010-02-04 05:44:44 +00002370 //
2371 // Note also that we DO NOT return at this point, because we still have
2372 // other tests to run.
Reid Kleckneref072032013-08-27 23:08:25 +00002373 QualType OldQType = Context.getCanonicalType(Old->getType());
2374 QualType NewQType = Context.getCanonicalType(New->getType());
John McCalle6a365d2010-12-19 02:44:49 +00002375 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckneref072032013-08-27 23:08:25 +00002376 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCalle6a365d2010-12-19 02:44:49 +00002377 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2378 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2379 bool RequiresAdjustment = false;
John McCallfb609142012-08-25 02:00:03 +00002380
Reid Kleckneref072032013-08-27 23:08:25 +00002381 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindolabc650912013-10-17 15:37:26 +00002382 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckneref072032013-08-27 23:08:25 +00002383 const FunctionType *FT =
2384 First->getType().getCanonicalType()->castAs<FunctionType>();
2385 FunctionType::ExtInfo FI = FT->getExtInfo();
2386 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2387 if (!NewCCExplicit) {
2388 // Inherit the CC from the previous declaration if it was specified
2389 // there but not here.
2390 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2391 RequiresAdjustment = true;
2392 } else {
2393 // Calling conventions aren't compatible, so complain.
2394 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2395 Diag(New->getLocation(), diag::err_cconv_change)
2396 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2397 << !FirstCCExplicit
2398 << (!FirstCCExplicit ? "" :
2399 FunctionType::getNameForCallConv(FI.getCC()));
John McCallfb609142012-08-25 02:00:03 +00002400
Reid Kleckneref072032013-08-27 23:08:25 +00002401 // Put the note on the first decl, since it is the one that matters.
2402 Diag(First->getLocation(), diag::note_previous_declaration);
2403 return true;
2404 }
John McCallf82b4e82010-02-04 05:44:44 +00002405 }
2406
John McCall04a67a62010-02-05 21:31:56 +00002407 // FIXME: diagnose the other way around?
John McCalle6a365d2010-12-19 02:44:49 +00002408 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2409 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2410 RequiresAdjustment = true;
John McCall04a67a62010-02-05 21:31:56 +00002411 }
2412
Douglas Gregord2c64902010-06-18 21:30:25 +00002413 // Merge regparm attribute.
Eli Friedmana49218e2011-04-09 08:18:08 +00002414 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2415 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2416 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregord2c64902010-06-18 21:30:25 +00002417 Diag(New->getLocation(), diag::err_regparm_mismatch)
2418 << NewType->getRegParmType()
2419 << OldType->getRegParmType();
2420 Diag(Old->getLocation(), diag::note_previous_declaration);
2421 return true;
2422 }
John McCalle6a365d2010-12-19 02:44:49 +00002423
2424 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2425 RequiresAdjustment = true;
2426 }
2427
Douglas Gregorcb1c9c32011-10-14 15:55:40 +00002428 // Merge ns_returns_retained attribute.
2429 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2430 if (NewTypeInfo.getProducesResult()) {
2431 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2432 Diag(Old->getLocation(), diag::note_previous_declaration);
2433 return true;
2434 }
2435
2436 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2437 RequiresAdjustment = true;
2438 }
2439
John McCalle6a365d2010-12-19 02:44:49 +00002440 if (RequiresAdjustment) {
Eli Friedman130fcc82013-09-06 21:09:09 +00002441 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2442 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2443 New->setType(QualType(AdjustedType, 0));
John McCalle6a365d2010-12-19 02:44:49 +00002444 NewQType = Context.getCanonicalType(New->getType());
Eli Friedman130fcc82013-09-06 21:09:09 +00002445 NewType = cast<FunctionType>(NewQType);
Douglas Gregord2c64902010-06-18 21:30:25 +00002446 }
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002447
2448 // If this redeclaration makes the function inline, we may need to add it to
2449 // UndefinedButUsed.
2450 if (!Old->isInlined() && New->isInlined() &&
2451 !New->hasAttr<GNUInlineAttr>() &&
2452 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2453 Old->isUsed(false) &&
2454 !Old->isDefined() && !New->isThisDeclarationADefinition())
2455 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2456 SourceLocation()));
2457
2458 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2459 // about it.
2460 if (New->hasAttr<GNUInlineAttr>() &&
2461 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2462 UndefinedButUsed.erase(Old->getCanonicalDecl());
2463 }
Douglas Gregord2c64902010-06-18 21:30:25 +00002464
David Blaikie4e4d0842012-03-11 07:00:24 +00002465 if (getLangOpts().CPlusPlus) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002466 // (C++98 13.1p2):
2467 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00002468 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002469 // cannot be overloaded.
Richard Smith60e141e2013-05-04 07:00:32 +00002470
2471 // Go back to the type source info to compare the declared return types,
Richard Smith37e849a2013-08-14 20:16:31 +00002472 // per C++1y [dcl.type.auto]p13:
Richard Smith60e141e2013-05-04 07:00:32 +00002473 // Redeclarations or specializations of a function or function template
2474 // with a declared return type that uses a placeholder type shall also
2475 // use that placeholder, not a deduced type.
2476 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2477 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2478 : OldType)->getResultType();
2479 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2480 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2481 : NewType)->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002482 QualType ResQT;
Richard Smitha41c97a2013-09-20 01:15:31 +00002483 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2484 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2485 New->isLocalExternDecl())) {
Richard Smith60e141e2013-05-04 07:00:32 +00002486 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2487 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002488 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2489 if (ResQT.isNull()) {
Argyrios Kyrtzidis1de34dd2011-02-05 05:54:49 +00002490 if (New->isCXXClassMember() && New->isOutOfLine())
2491 Diag(New->getLocation(),
2492 diag::err_member_def_does_not_match_ret_type) << New;
2493 else
2494 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00002495 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2496 return true;
2497 }
2498 else
2499 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002500 }
2501
Richard Smith60e141e2013-05-04 07:00:32 +00002502 QualType OldReturnType = OldType->getResultType();
2503 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2504 if (OldReturnType != NewReturnType) {
2505 // If this function has a deduced return type and has already been
2506 // defined, copy the deduced value from the old declaration.
2507 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2508 if (OldAT && OldAT->isDeduced()) {
Richard Smith37e849a2013-08-14 20:16:31 +00002509 New->setType(
2510 SubstAutoType(New->getType(),
2511 OldAT->isDependentType() ? Context.DependentTy
2512 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002513 NewQType = Context.getCanonicalType(
Richard Smith37e849a2013-08-14 20:16:31 +00002514 SubstAutoType(NewQType,
2515 OldAT->isDependentType() ? Context.DependentTy
2516 : OldAT->getDeducedType()));
Richard Smith60e141e2013-05-04 07:00:32 +00002517 }
2518 }
2519
2520 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2521 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002522 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00002523 // Preserve triviality.
2524 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichete1e96a62011-05-14 19:17:07 +00002525
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002526 // MSVC allows explicit template specialization at class scope:
2527 // 2 CXMethodDecls referring to the same function will be injected.
2528 // We don't want a redeclartion error.
2529 bool IsClassScopeExplicitSpecialization =
2530 OldMethod->isFunctionTemplateSpecialization() &&
2531 NewMethod->isFunctionTemplateSpecialization();
John McCall3d043362010-04-13 07:45:41 +00002532 bool isFriend = NewMethod->getFriendObjectKind();
2533
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002534 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2535 !IsClassScopeExplicitSpecialization) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002536 // -- Member function declarations with the same name and the
2537 // same parameter types cannot be overloaded if any of them
2538 // is a static member function declaration.
Eli Friedmanfa0d3f82013-06-19 22:43:55 +00002539 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002540 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2541 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2542 return true;
2543 }
Richard Smith838925d2012-07-13 04:12:04 +00002544
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002545 // C++ [class.mem]p1:
2546 // [...] A member shall not be declared twice in the
2547 // member-specification, except that a nested class or member
2548 // class template can be declared and then later defined.
Richard Smith838925d2012-07-13 04:12:04 +00002549 if (ActiveTemplateInstantiations.empty()) {
2550 unsigned NewDiag;
2551 if (isa<CXXConstructorDecl>(OldMethod))
2552 NewDiag = diag::err_constructor_redeclared;
2553 else if (isa<CXXDestructorDecl>(NewMethod))
2554 NewDiag = diag::err_destructor_redeclared;
2555 else if (isa<CXXConversionDecl>(NewMethod))
2556 NewDiag = diag::err_conv_function_redeclared;
2557 else
2558 NewDiag = diag::err_member_redeclared;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002559
Richard Smith838925d2012-07-13 04:12:04 +00002560 Diag(New->getLocation(), NewDiag);
2561 } else {
2562 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2563 << New << New->getType();
2564 }
Douglas Gregor3e41d602009-02-13 23:20:09 +00002565 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00002566
2567 // Complain if this is an explicit declaration of a special
2568 // member that was initially declared implicitly.
2569 //
2570 // As an exception, it's okay to befriend such methods in order
2571 // to permit the implicit constructor/destructor/operator calls.
2572 } else if (OldMethod->isImplicit()) {
2573 if (isFriend) {
2574 NewMethod->setImplicit();
2575 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002576 Diag(NewMethod->getLocation(),
2577 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00002578 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00002579 return true;
2580 }
Richard Smithf4fe8432012-06-08 01:30:54 +00002581 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Sean Hunt001cad92011-05-10 00:49:42 +00002582 Diag(NewMethod->getLocation(),
2583 diag::err_definition_of_explicitly_defaulted_member)
2584 << getSpecialMember(OldMethod);
2585 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002586 }
2587 }
2588
Richard Smithcd8ab512013-01-17 01:30:42 +00002589 // C++11 [dcl.attr.noreturn]p1:
2590 // The first declaration of a function shall specify the noreturn
2591 // attribute if any declaration of that function specifies the noreturn
2592 // attribute.
2593 if (New->hasAttr<CXX11NoReturnAttr>() &&
2594 !Old->hasAttr<CXX11NoReturnAttr>()) {
2595 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2596 diag::err_noreturn_missing_on_first_decl);
Rafael Espindolabc650912013-10-17 15:37:26 +00002597 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithcd8ab512013-01-17 01:30:42 +00002598 diag::note_noreturn_missing_first_decl);
2599 }
2600
Richard Smith3a2b7a12013-01-28 22:42:45 +00002601 // C++11 [dcl.attr.depend]p2:
2602 // The first declaration of a function shall specify the
2603 // carries_dependency attribute for its declarator-id if any declaration
2604 // of the function specifies the carries_dependency attribute.
2605 if (New->hasAttr<CarriesDependencyAttr>() &&
2606 !Old->hasAttr<CarriesDependencyAttr>()) {
2607 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2608 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindolabc650912013-10-17 15:37:26 +00002609 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002610 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2611 }
2612
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002613 // (C++98 8.3.5p3):
2614 // All declarations for a function shall agree exactly in both the
2615 // return type and the parameter-type-list.
John McCalle6a365d2010-12-19 02:44:49 +00002616 // We also want to respect all the extended bits except noreturn.
2617
2618 // noreturn should now match unless the old type info didn't have it.
2619 QualType OldQTypeForComparison = OldQType;
2620 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2621 assert(OldQType == QualType(OldType, 0));
2622 const FunctionType *OldTypeForComparison
2623 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2624 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2625 assert(OldQTypeForComparison.isCanonical());
2626 }
2627
Rafael Espindola950fee22013-02-14 01:18:37 +00002628 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokera8a2ebe2013-10-22 22:53:01 +00002629 // As a special case, retain the language linkage from previous
2630 // declarations of a friend function as an extension.
2631 //
2632 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2633 // and is useful because there's otherwise no way to specify language
2634 // linkage within class scope.
2635 //
2636 // Check cautiously as the friend object kind isn't yet complete.
2637 if (New->getFriendObjectKind() != Decl::FOK_None) {
2638 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2639 Diag(Old->getLocation(), PrevDiag);
2640 } else {
2641 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2642 Diag(Old->getLocation(), PrevDiag);
2643 return true;
2644 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00002645 }
2646
John McCalle6a365d2010-12-19 02:44:49 +00002647 if (OldQTypeForComparison == NewQType)
Richard Smithdd9459f2013-08-13 18:18:50 +00002648 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002649
Richard Smitha41c97a2013-09-20 01:15:31 +00002650 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2651 New->isLocalExternDecl()) {
2652 // It's OK if we couldn't merge types for a local function declaraton
2653 // if either the old or new type is dependent. We'll merge the types
2654 // when we instantiate the function.
2655 return false;
2656 }
2657
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002658 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00002659 }
Chris Lattner04421082008-04-08 04:40:51 +00002660
2661 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002662 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002663 if (!getLangOpts().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00002664 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00002665 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2666 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002667 const FunctionProtoType *OldProto = 0;
Richard Smithdd9459f2013-08-13 18:18:50 +00002668 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002669 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00002670 // The old declaration provided a function prototype, but the
2671 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00002672 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002673 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregor68719812009-02-16 18:20:44 +00002674 OldProto->arg_type_end());
2675 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002676 ParamTypes,
John McCalle23cf432010-12-14 08:05:40 +00002677 OldProto->getExtProtoInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00002678 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00002679 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00002680
2681 // Synthesize a parameter for each argument type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002682 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00002683 for (FunctionProtoType::arg_type_iterator
2684 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00002685 ParamEnd = OldProto->arg_type_end();
2686 ParamType != ParamEnd; ++ParamType) {
2687 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002688 SourceLocation(),
Douglas Gregor450da982009-02-16 20:58:07 +00002689 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002690 *ParamType, /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002691 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002692 0);
John McCallfb44de92011-05-01 22:35:37 +00002693 Param->setScopeInfo(0, Params.size());
Douglas Gregor450da982009-02-16 20:58:07 +00002694 Param->setImplicit();
2695 Params.push_back(Param);
2696 }
2697
David Blaikie4278c652011-09-21 18:16:56 +00002698 New->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00002699 }
Douglas Gregor68719812009-02-16 18:20:44 +00002700
Richard Smithdd9459f2013-08-13 18:18:50 +00002701 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattner04421082008-04-08 04:40:51 +00002702 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00002703
Douglas Gregorc8376562009-03-06 22:43:54 +00002704 // GNU C permits a K&R definition to follow a prototype declaration
2705 // if the declared types of the parameters in the K&R definition
2706 // match the types in the prototype declaration, even when the
2707 // promoted types of the parameters from the K&R definition differ
2708 // from the types in the prototype. GCC then keeps the types from
2709 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002710 //
2711 // If a variadic prototype is followed by a non-variadic K&R definition,
2712 // the K&R definition becomes variadic. This is sort of an edge case, but
2713 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2714 // C99 6.9.1p8.
David Blaikie4e4d0842012-03-11 07:00:24 +00002715 if (!getLangOpts().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002716 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00002717 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00002718 Old->getNumParams() == New->getNumParams()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002719 SmallVector<QualType, 16> ArgTypes;
2720 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00002721 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00002722 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002723 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00002724 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Douglas Gregorc8376562009-03-06 22:43:54 +00002726 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002727 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2728 NewProto->getResultType());
2729 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00002730 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002731 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002732 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2733 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00002734 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00002735 NewProto->getArgType(Idx))) {
2736 ArgTypes.push_back(NewParm->getType());
2737 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00002738 NewParm->getType(),
2739 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002740 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00002741 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2742 Warnings.push_back(Warn);
2743 ArgTypes.push_back(NewParm->getType());
2744 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002745 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00002746 }
2747
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002748 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00002749 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2750 Diag(Warnings[Warn].NewParm->getLocation(),
2751 diag::ext_param_promoted_not_compatible_with_prototype)
2752 << Warnings[Warn].PromotedType
2753 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00002754 if (Warnings[Warn].OldParm->getLocation().isValid())
2755 Diag(Warnings[Warn].OldParm->getLocation(),
2756 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00002757 }
2758
Richard Smithdd9459f2013-08-13 18:18:50 +00002759 if (MergeTypeWithOld)
2760 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2761 OldProto->getExtProtoInfo()));
2762 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregorc8376562009-03-06 22:43:54 +00002763 }
2764
2765 // Fall through to diagnose conflicting types.
2766 }
2767
John McCall088831d2013-04-14 08:50:55 +00002768 // A function that has already been declared has been redeclared or
2769 // defined with a different type; show an appropriate diagnostic.
2770
2771 // If the previous declaration was an implicitly-generated builtin
2772 // declaration, then at the very least we should use a specialized note.
2773 unsigned BuiltinID;
2774 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2775 // If it's actually a library-defined builtin function like 'malloc'
2776 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002777 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002778 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2779 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2780 << Old << Old->getType();
John McCall088831d2013-04-14 08:50:55 +00002781
2782 // If this is a global redeclaration, just forget hereafter
2783 // about the "builtin-ness" of the function.
2784 //
2785 // Doing this for local extern declarations is problematic. If
2786 // the builtin declaration remains visible, a second invalid
2787 // local declaration will produce a hard error; if it doesn't
2788 // remain visible, a single bogus local redeclaration (which is
2789 // actually only a warning) could break all the downstream code.
Richard Smitha41c97a2013-09-20 01:15:31 +00002790 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCall088831d2013-04-14 08:50:55 +00002791 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2792
Douglas Gregor374e1562009-03-23 17:47:24 +00002793 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002794 }
Steve Naroff837618c2008-01-16 15:01:34 +00002795
Douglas Gregorcda9c672009-02-16 17:45:42 +00002796 PrevDiag = diag::note_previous_builtin_declaration;
2797 }
2798
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002799 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00002800 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00002801 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002802}
2803
Douglas Gregor04495c82009-02-24 01:23:02 +00002804/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00002805/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00002806///
2807/// This routine handles the merging of attributes and other
Alp Toker89673e02013-10-22 09:00:49 +00002808/// properties of function declarations from the old declaration to
Douglas Gregor04495c82009-02-24 01:23:02 +00002809/// the new declaration, once we know that New is in fact a
2810/// redeclaration of Old.
2811///
2812/// \returns false
James Molloy9cda03f2012-03-13 08:55:35 +00002813bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smithdd9459f2013-08-13 18:18:50 +00002814 Scope *S, bool MergeTypeWithOld) {
Douglas Gregor04495c82009-02-24 01:23:02 +00002815 // Merge the attributes
Douglas Gregor27c6da22012-01-01 20:30:41 +00002816 mergeDeclAttributes(New, Old);
Douglas Gregor04495c82009-02-24 01:23:02 +00002817
Douglas Gregor04495c82009-02-24 01:23:02 +00002818 // Merge "pure" flag.
2819 if (Old->isPure())
2820 New->setPure();
2821
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002822 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00002823 if (Old->getMostRecentDecl()->isUsed(false))
2824 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00002825
John McCalleca5d222011-03-02 04:00:57 +00002826 // Merge attributes from the parameters. These can mismatch with K&R
2827 // declarations.
2828 if (New->getNumParams() == Old->getNumParams())
2829 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2830 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smith3a2b7a12013-01-28 22:42:45 +00002831 *this);
John McCalleca5d222011-03-02 04:00:57 +00002832
David Blaikie4e4d0842012-03-11 07:00:24 +00002833 if (getLangOpts().CPlusPlus)
James Molloy9cda03f2012-03-13 08:55:35 +00002834 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregor04495c82009-02-24 01:23:02 +00002835
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002836 // Merge the function types so the we get the composite types for the return
Richard Smithdd9459f2013-08-13 18:18:50 +00002837 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2838 // was visible.
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002839 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smithdd9459f2013-08-13 18:18:50 +00002840 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00002841 New->setType(Merged);
2842
Douglas Gregor04495c82009-02-24 01:23:02 +00002843 return false;
2844}
2845
John McCallf85e1932011-06-15 23:02:42 +00002846
John McCalleca5d222011-03-02 04:00:57 +00002847void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor27c6da22012-01-01 20:30:41 +00002848 ObjCMethodDecl *oldMethod) {
John McCall6c2c2502011-07-22 02:45:48 +00002849
Fariborz Jahanian1ea67442012-06-05 21:14:46 +00002850 // Merge the attributes, including deprecated/unavailable
Ted Kremenekcb344392013-04-06 00:34:27 +00002851 AvailabilityMergeKind MergeKind =
2852 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2853 : AMK_Override;
2854 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCalleca5d222011-03-02 04:00:57 +00002855
2856 // Merge attributes from the parameters.
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002857 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2858 oe = oldMethod->param_end();
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002859 for (ObjCMethodDecl::param_iterator
John McCalleca5d222011-03-02 04:00:57 +00002860 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002861 ni != ne && oi != oe; ++ni, ++oi)
Richard Smith3a2b7a12013-01-28 22:42:45 +00002862 mergeParamDeclAttributes(*ni, *oi, *this);
John McCall6c2c2502011-07-22 02:45:48 +00002863
Douglas Gregorf4d918f2013-01-15 22:43:08 +00002864 CheckObjCMethodOverride(newMethod, oldMethod);
John McCalleca5d222011-03-02 04:00:57 +00002865}
2866
Sebastian Redl60618fa2011-03-12 11:50:43 +00002867/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2868/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith34b41d92011-02-20 03:19:35 +00002869/// emitting diagnostics as appropriate.
2870///
2871/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002872/// to here in AddInitializerToDecl. We can't check them before the initializer
2873/// is attached.
Richard Smithdd9459f2013-08-13 18:18:50 +00002874void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2875 bool MergeTypeWithOld) {
Richard Smith34b41d92011-02-20 03:19:35 +00002876 if (New->isInvalidDecl() || Old->isInvalidDecl())
2877 return;
2878
2879 QualType MergedT;
David Blaikie4e4d0842012-03-11 07:00:24 +00002880 if (getLangOpts().CPlusPlus) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00002881 if (New->getType()->isUndeducedType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00002882 // We don't know what the new type is until the initializer is attached.
2883 return;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002884 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2885 // These could still be something that needs exception specs checked.
2886 return MergeVarDeclExceptionSpecs(New, Old);
2887 }
Richard Smith34b41d92011-02-20 03:19:35 +00002888 // C++ [basic.link]p10:
2889 // [...] the types specified by all declarations referring to a given
2890 // object or function shall be identical, except that declarations for an
2891 // array object can specify array types that differ by the presence or
2892 // absence of a major array bound (8.3.4).
2893 else if (Old->getType()->isIncompleteArrayType() &&
2894 New->getType()->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002895 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2896 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2897 if (Context.hasSameType(OldArray->getElementType(),
2898 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002899 MergedT = New->getType();
2900 } else if (Old->getType()->isArrayType() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00002901 New->getType()->isIncompleteArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00002902 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2903 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2904 if (Context.hasSameType(OldArray->getElementType(),
2905 NewArray->getElementType()))
Richard Smith34b41d92011-02-20 03:19:35 +00002906 MergedT = Old->getType();
Richard Smitha41c97a2013-09-20 01:15:31 +00002907 } else if (New->getType()->isObjCObjectPointerType() &&
2908 Old->getType()->isObjCObjectPointerType()) {
2909 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2910 Old->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00002911 }
2912 } else {
Richard Smitha41c97a2013-09-20 01:15:31 +00002913 // C 6.2.7p2:
2914 // All declarations that refer to the same object or function shall have
2915 // compatible type.
Richard Smith34b41d92011-02-20 03:19:35 +00002916 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2917 }
2918 if (MergedT.isNull()) {
Richard Smithdd9459f2013-08-13 18:18:50 +00002919 // It's OK if we couldn't merge types if either type is dependent, for a
2920 // block-scope variable. In other cases (static data members of class
2921 // templates, variable templates, ...), we require the types to be
2922 // equivalent.
2923 // FIXME: The C++ standard doesn't say anything about this.
2924 if ((New->getType()->isDependentType() ||
2925 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2926 // If the old type was dependent, we can't merge with it, so the new type
2927 // becomes dependent for now. We'll reproduce the original type when we
2928 // instantiate the TypeSourceInfo for the variable.
2929 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2930 New->setType(Context.DependentTy);
2931 return;
2932 }
2933
2934 // FIXME: Even if this merging succeeds, some other non-visible declaration
2935 // of this variable might have an incompatible type. For instance:
2936 //
2937 // extern int arr[];
2938 // void f() { extern int arr[2]; }
2939 // void g() { extern int arr[3]; }
2940 //
2941 // Neither C nor C++ requires a diagnostic for this, but we should still try
2942 // to diagnose it.
Richard Smith34b41d92011-02-20 03:19:35 +00002943 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikiea405b252012-09-20 18:38:57 +00002944 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00002945 Diag(Old->getLocation(), diag::note_previous_definition);
2946 return New->setInvalidDecl();
2947 }
John McCall5b8740f2013-04-01 18:34:28 +00002948
2949 // Don't actually update the type on the new declaration if the old
Richard Smith99a72382013-09-03 21:00:58 +00002950 // declaration was an extern declaration in a different scope.
Richard Smithdd9459f2013-08-13 18:18:50 +00002951 if (MergeTypeWithOld)
John McCall5b8740f2013-04-01 18:34:28 +00002952 New->setType(MergedT);
Richard Smith34b41d92011-02-20 03:19:35 +00002953}
2954
Richard Smith99a72382013-09-03 21:00:58 +00002955static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2956 LookupResult &Previous) {
2957 // C11 6.2.7p4:
2958 // For an identifier with internal or external linkage declared
2959 // in a scope in which a prior declaration of that identifier is
2960 // visible, if the prior declaration specifies internal or
2961 // external linkage, the type of the identifier at the later
2962 // declaration becomes the composite type.
2963 //
2964 // If the variable isn't visible, we do not merge with its type.
2965 if (Previous.isShadowed())
2966 return false;
2967
2968 if (S.getLangOpts().CPlusPlus) {
2969 // C++11 [dcl.array]p3:
2970 // If there is a preceding declaration of the entity in the same
2971 // scope in which the bound was specified, an omitted array bound
2972 // is taken to be the same as in that earlier declaration.
2973 return NewVD->isPreviousDeclInSameBlockScope() ||
2974 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2975 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2976 } else {
2977 // If the old declaration was function-local, don't merge with its
2978 // type unless we're in the same function.
2979 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2980 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2981 }
2982}
2983
Reid Spencer5f016e22007-07-11 17:01:13 +00002984/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2985/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2986/// situation, merging decls or emitting diagnostics as appropriate.
2987///
Mike Stump1eb44332009-09-09 15:08:12 +00002988/// Tentative definition rules (C99 6.9.2p2) are checked by
2989/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002990/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00002991///
Richard Smith99a72382013-09-03 21:00:58 +00002992void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall68263142009-11-18 22:49:29 +00002993 // If the new decl is already invalid, don't do any other checking.
2994 if (New->isInvalidDecl())
2995 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002996
Larisse Voufo4a919892013-08-14 03:09:19 +00002997 // Verify the old decl was also a variable or variable template.
John McCall68263142009-11-18 22:49:29 +00002998 VarDecl *Old = 0;
Larisse Voufo4a919892013-08-14 03:09:19 +00002999 if (Previous.isSingleResult() &&
3000 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo567f9172013-08-22 00:59:14 +00003001 if (New->getDescribedVarTemplate())
Larisse Voufo4a919892013-08-14 03:09:19 +00003002 Old = Old->getDescribedVarTemplate() ? Old : 0;
3003 else
3004 Old = Old->getDescribedVarTemplate() ? 0 : Old;
3005 }
3006 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003007 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00003008 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00003009 Diag(Previous.getRepresentativeDecl()->getLocation(),
3010 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003011 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003012 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003013
Rafael Espindola90cc3902013-04-15 12:49:13 +00003014 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3015 return;
3016
Douglas Gregor7f6ff022010-08-30 14:32:14 +00003017 // C++ [class.mem]p1:
3018 // A member shall not be declared twice in the member-specification [...]
3019 //
3020 // Here, we need only consider static data members.
3021 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3022 Diag(New->getLocation(), diag::err_duplicate_member)
3023 << New->getIdentifier();
3024 Diag(Old->getLocation(), diag::note_previous_declaration);
3025 New->setInvalidDecl();
3026 }
3027
Douglas Gregor27c6da22012-01-01 20:30:41 +00003028 mergeDeclAttributes(New, Old);
David Blaikied662a792011-10-19 22:56:21 +00003029 // Warn if an already-declared variable is made a weak_import in a subsequent
3030 // declaration
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00003031 if (New->getAttr<WeakImportAttr>() &&
3032 Old->getStorageClass() == SC_None &&
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003033 !Old->getAttr<WeakImportAttr>()) {
3034 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3035 Diag(Old->getLocation(), diag::note_previous_definition);
3036 // Remove weak_import attribute on new declaration.
Fariborz Jahanianc3ca14d2011-06-23 17:50:10 +00003037 New->dropAttr<WeakImportAttr>();
Fariborz Jahaniand5431302011-06-22 22:08:50 +00003038 }
Chris Lattnerddee4232008-03-03 03:28:21 +00003039
Richard Smith34b41d92011-02-20 03:19:35 +00003040 // Merge the types.
Richard Smith99a72382013-09-03 21:00:58 +00003041 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3042
Richard Smith34b41d92011-02-20 03:19:35 +00003043 if (New->isInvalidDecl())
3044 return;
Douglas Gregor656de632009-03-11 23:52:16 +00003045
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003046 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCalld931b082010-08-26 03:08:43 +00003047 if (New->getStorageClass() == SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003048 !New->isStaticDataMember() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00003049 Old->hasExternalFormalLinkage()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003050 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003051 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003052 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003053 }
Mike Stump1eb44332009-09-09 15:08:12 +00003054 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003055 // For an identifier declared with the storage-class specifier
3056 // extern in a scope in which a prior declaration of that
3057 // identifier is visible,23) if the prior declaration specifies
3058 // internal or external linkage, the linkage of the identifier at
3059 // the later declaration is the same as the linkage specified at
3060 // the prior declaration. If no prior declaration is visible, or
3061 // if the prior declaration specifies no linkage, then the
3062 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00003063 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00003064 /* Okay */;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003065 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindolaea4b1112013-04-04 21:21:25 +00003066 !New->isStaticDataMember() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003067 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003068 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003069 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003070 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00003071 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003072
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003073 // Check if extern is followed by non-extern and vice-versa.
3074 if (New->hasExternalStorage() &&
3075 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3076 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3077 Diag(Old->getLocation(), diag::note_previous_definition);
3078 return New->setInvalidDecl();
3079 }
Rafael Espindola80a86892013-04-04 02:47:57 +00003080 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3081 !New->hasExternalStorage()) {
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00003082 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3083 Diag(Old->getLocation(), diag::note_previous_definition);
3084 return New->setInvalidDecl();
3085 }
3086
Steve Naroff094cefb2008-09-17 14:05:40 +00003087 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00003089 // FIXME: The test for external storage here seems wrong? We still
3090 // need to check for mismatches.
3091 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00003092 // Don't complain about out-of-line definitions of static members.
3093 !(Old->getLexicalDeclContext()->isRecord() &&
3094 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00003095 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003096 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003097 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 }
Douglas Gregor275a3692009-03-10 23:43:53 +00003099
Richard Smith38afbc72013-04-13 02:43:54 +00003100 if (New->getTLSKind() != Old->getTLSKind()) {
3101 if (!Old->getTLSKind()) {
3102 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3103 Diag(Old->getLocation(), diag::note_previous_declaration);
3104 } else if (!New->getTLSKind()) {
3105 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3106 Diag(Old->getLocation(), diag::note_previous_declaration);
3107 } else {
3108 // Do not allow redeclaration to change the variable between requiring
3109 // static and dynamic initialization.
3110 // FIXME: GCC allows this, but uses the TLS keyword on the first
3111 // declaration to determine the kind. Do we need to be compatible here?
3112 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3113 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3114 Diag(Old->getLocation(), diag::note_previous_declaration);
3115 }
Eli Friedman63054b32009-04-19 20:27:55 +00003116 }
3117
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003118 // C++ doesn't have tentative definitions, so go right ahead and check here.
3119 const VarDecl *Def;
David Blaikie4e4d0842012-03-11 07:00:24 +00003120 if (getLangOpts().CPlusPlus &&
Sebastian Redl6c048a92010-02-03 02:08:48 +00003121 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003122 (Def = Old->getDefinition())) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003123 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redl4cae1b32010-02-02 18:35:11 +00003124 Diag(Def->getLocation(), diag::note_previous_definition);
3125 New->setInvalidDecl();
3126 return;
3127 }
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003128
Rafael Espindola950fee22013-02-14 01:18:37 +00003129 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolae57e3d32012-12-27 03:56:20 +00003130 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3131 Diag(Old->getLocation(), diag::note_previous_definition);
3132 New->setInvalidDecl();
3133 return;
3134 }
3135
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003136 // Merge "used" flag.
Rafael Espindolae7bd89a2013-10-23 16:46:34 +00003137 if (Old->getMostRecentDecl()->isUsed(false))
3138 New->setIsUsed();
Rafael Espindola8dbf6972012-11-25 14:07:59 +00003139
Douglas Gregor275a3692009-03-10 23:43:53 +00003140 // Keep a chain of previous declarations.
Rafael Espindolabc650912013-10-17 15:37:26 +00003141 New->setPreviousDecl(Old);
John McCall46460a62010-01-20 21:53:11 +00003142
3143 // Inherit access appropriately.
3144 New->setAccess(Old->getAccess());
Larisse Voufo567f9172013-08-22 00:59:14 +00003145
3146 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3147 if (New->isStaticDataMember() && New->isOutOfLine())
3148 VTD->setAccess(New->getAccess());
3149 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003150}
3151
3152/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3153/// no declarator (e.g. "struct foo;") is parsed.
John McCalld226f652010-08-21 09:40:31 +00003154Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallac4df242011-03-22 23:00:04 +00003155 DeclSpec &DS) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00003156 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth0f4be742011-05-03 18:35:10 +00003157}
3158
Eli Friedman5e867c82013-07-10 00:30:46 +00003159static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00003160 if (!S.Context.getLangOpts().CPlusPlus)
3161 return;
3162
Eli Friedman5e867c82013-07-10 00:30:46 +00003163 if (isa<CXXRecordDecl>(Tag->getParent())) {
3164 // If this tag is the direct child of a class, number it if
3165 // it is anonymous.
3166 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3167 return;
3168 MangleNumberingContext &MCtx =
3169 S.Context.getManglingNumberContext(Tag->getParent());
3170 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3171 return;
3172 }
3173
3174 // If this tag isn't a direct child of a class, number it if it is local.
3175 Decl *ManglingContextDecl;
3176 if (MangleNumberingContext *MCtx =
3177 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3178 ManglingContextDecl)) {
3179 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3180 }
3181}
3182
Chandler Carruth0f4be742011-05-03 18:35:10 +00003183/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithc7f81162013-03-18 22:52:47 +00003184/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth0f4be742011-05-03 18:35:10 +00003185/// parameters to cope with template friend declarations.
3186Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3187 DeclSpec &DS,
Richard Smithc7f81162013-03-18 22:52:47 +00003188 MultiTemplateParamsArg TemplateParams,
3189 bool IsExplicitInstantiation) {
John McCalle3af0232009-10-07 23:34:25 +00003190 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003191 TagDecl *Tag = 0;
3192 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3193 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003194 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003195 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003196 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallb3d87482010-08-24 05:47:05 +00003197 TagD = DS.getRepAsDecl();
John McCalle3af0232009-10-07 23:34:25 +00003198
3199 if (!TagD) // We probably had an error
John McCalld226f652010-08-21 09:40:31 +00003200 return 0;
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003201
John McCall67d1a672009-08-06 02:15:43 +00003202 // Note that the above type specs guarantee that the
3203 // type rep is a Decl, whereas in many of the others
3204 // it's a Type.
Peter Collingbourne0661bd0c2011-10-23 17:07:16 +00003205 if (isa<TagDecl>(TagD))
3206 Tag = cast<TagDecl>(TagD);
3207 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3208 Tag = CTD->getTemplatedDecl();
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00003209 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003210
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003211 if (Tag) {
Eli Friedman5e867c82013-07-10 00:30:46 +00003212 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003213 Tag->setFreeStanding();
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +00003214 if (Tag->isInvalidDecl())
3215 return Tag;
3216 }
Argyrios Kyrtzidis717a20b2011-09-30 22:11:31 +00003217
Nuno Lopes0a8bab02009-12-17 11:35:26 +00003218 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3219 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3220 // or incomplete types shall not be restrict-qualified."
3221 if (TypeQuals & DeclSpec::TQ_restrict)
3222 Diag(DS.getRestrictSpecLoc(),
3223 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3224 << DS.getSourceRange();
3225 }
3226
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003227 if (DS.isConstexprSpecified()) {
3228 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3229 // and definitions of functions and variables.
3230 if (Tag)
3231 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3232 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3233 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003234 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3235 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003236 else
3237 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3238 // Don't emit warnings after this error.
3239 return TagD;
3240 }
3241
Richard Smithc7f81162013-03-18 22:52:47 +00003242 DiagnoseFunctionSpecifiers(DS);
3243
Douglas Gregord85bea22009-09-26 06:47:28 +00003244 if (DS.isFriendSpecified()) {
John McCall9a34edb2010-10-19 01:40:49 +00003245 // If we're dealing with a decl but not a TagDecl, assume that
3246 // whatever routines created it handled the friendship aspect.
3247 if (TagD && !Tag)
John McCalld226f652010-08-21 09:40:31 +00003248 return 0;
Chandler Carruth0f4be742011-05-03 18:35:10 +00003249 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregord85bea22009-09-26 06:47:28 +00003250 }
John McCallac4df242011-03-22 23:00:04 +00003251
Richard Smithc7f81162013-03-18 22:52:47 +00003252 CXXScopeSpec &SS = DS.getTypeSpecScope();
3253 bool IsExplicitSpecialization =
3254 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3255 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3256 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3257 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3258 // nested-name-specifier unless it is an explicit instantiation
3259 // or an explicit specialization.
3260 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3261 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3262 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3263 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3264 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3265 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3266 << SS.getRange();
3267 return 0;
3268 }
3269
3270 // Track whether this decl-specifier declares anything.
3271 bool DeclaresAnything = true;
3272
3273 // Handle anonymous struct definitions.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003274 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall5e1cdac2011-10-07 06:10:15 +00003275 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00003276 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003277 if (getLangOpts().CPlusPlus ||
Douglas Gregora71c1292009-03-06 23:06:59 +00003278 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00003279 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00003280
Richard Smithc7f81162013-03-18 22:52:47 +00003281 DeclaresAnything = false;
Douglas Gregora71c1292009-03-06 23:06:59 +00003282 }
Francois Pichet8e161ed2010-11-23 06:07:27 +00003283 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003284
Richard Smithc7f81162013-03-18 22:52:47 +00003285 // Check for Microsoft C extension: anonymous struct member.
David Blaikie4e4d0842012-03-11 07:00:24 +00003286 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet8e161ed2010-11-23 06:07:27 +00003287 CurContext->isRecord() &&
3288 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3289 // Handle 2 kinds of anonymous struct:
3290 // struct STRUCT;
3291 // and
3292 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3293 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCall5e1cdac2011-10-07 06:10:15 +00003294 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet8e161ed2010-11-23 06:07:27 +00003295 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3296 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00003297 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet8e161ed2010-11-23 06:07:27 +00003298 << DS.getSourceRange();
3299 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3300 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003301 }
Richard Smithc7f81162013-03-18 22:52:47 +00003302
3303 // Skip all the checks below if we have a type error.
3304 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3305 (TagD && TagD->isInvalidDecl()))
3306 return TagD;
3307
3308 if (getLangOpts().CPlusPlus &&
Douglas Gregora131d0f2010-07-13 06:24:26 +00003309 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3310 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3311 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithc7f81162013-03-18 22:52:47 +00003312 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3313 DeclaresAnything = false;
John McCallac4df242011-03-22 23:00:04 +00003314
John McCallac4df242011-03-22 23:00:04 +00003315 if (!DS.isMissingDeclaratorOk()) {
Richard Smithc7f81162013-03-18 22:52:47 +00003316 // Customize diagnostic for a typedef missing a name.
3317 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003318 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregora0ebd602010-07-16 15:40:40 +00003319 << DS.getSourceRange();
Richard Smithc7f81162013-03-18 22:52:47 +00003320 else
3321 DeclaresAnything = false;
Sebastian Redla4ed0d82008-12-28 15:28:59 +00003322 }
Mike Stump1eb44332009-09-09 15:08:12 +00003323
Richard Smithc7f81162013-03-18 22:52:47 +00003324 if (DS.isModulePrivateSpecified() &&
Douglas Gregore3895852011-09-12 18:37:38 +00003325 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3326 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3327 << Tag->getTagKind()
3328 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3329
Richard Smithc7f81162013-03-18 22:52:47 +00003330 ActOnDocumentableDecl(TagD);
3331
3332 // C 6.7/2:
3333 // A declaration [...] shall declare at least a declarator [...], a tag,
3334 // or the members of an enumeration.
3335 // C++ [dcl.dcl]p3:
3336 // [If there are no declarators], and except for the declaration of an
3337 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3338 // names into the program, or shall redeclare a name introduced by a
3339 // previous declaration.
3340 if (!DeclaresAnything) {
3341 // In C, we allow this as a (popular) extension / bug. Don't bother
3342 // producing further diagnostics for redundant qualifiers after this.
3343 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3344 return TagD;
3345 }
3346
3347 // C++ [dcl.stc]p1:
3348 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3349 // init-declarator-list of the declaration shall not be empty.
3350 // C++ [dcl.fct.spec]p1:
3351 // If a cv-qualifier appears in a decl-specifier-seq, the
3352 // init-declarator-list of the declaration shall not be empty.
3353 //
3354 // Spurious qualifiers here appear to be valid in C.
3355 unsigned DiagID = diag::warn_standalone_specifier;
3356 if (getLangOpts().CPlusPlus)
3357 DiagID = diag::ext_standalone_specifier;
3358
3359 // Note that a linkage-specification sets a storage class, but
3360 // 'extern "C" struct foo;' is actually valid and not theoretically
3361 // useless.
3362 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3363 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3364 Diag(DS.getStorageClassSpecLoc(), DiagID)
3365 << DeclSpec::getSpecifierName(SCS);
3366
Richard Smithec642442013-04-12 22:46:28 +00003367 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3368 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3369 << DeclSpec::getSpecifierName(TSCS);
Richard Smithc7f81162013-03-18 22:52:47 +00003370 if (DS.getTypeQualifiers()) {
3371 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3372 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3373 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3374 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3375 // Restrict is covered above.
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003376 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3377 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithc7f81162013-03-18 22:52:47 +00003378 }
3379
Eli Friedmanfc038e92011-12-17 00:36:09 +00003380 // Warn about ignored type attributes, for example:
3381 // __attribute__((aligned)) struct A;
Bill Wendlingad017fa2012-12-20 19:22:21 +00003382 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmanfc038e92011-12-17 00:36:09 +00003383 if (!DS.getAttributes().empty()) {
3384 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3385 if (TypeSpecType == DeclSpec::TST_class ||
3386 TypeSpecType == DeclSpec::TST_struct ||
Joao Matos6666ed42012-08-31 18:45:21 +00003387 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmanfc038e92011-12-17 00:36:09 +00003388 TypeSpecType == DeclSpec::TST_union ||
3389 TypeSpecType == DeclSpec::TST_enum) {
3390 AttributeList* attrs = DS.getAttributes().getList();
3391 while (attrs) {
Michael Han45bed132012-10-04 16:42:52 +00003392 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmanfc038e92011-12-17 00:36:09 +00003393 << attrs->getName()
3394 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3395 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matos6666ed42012-08-31 18:45:21 +00003396 TypeSpecType == DeclSpec::TST_union ? 2 :
3397 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmanfc038e92011-12-17 00:36:09 +00003398 attrs = attrs->getNext();
3399 }
3400 }
3401 }
John McCallac4df242011-03-22 23:00:04 +00003402
John McCalld226f652010-08-21 09:40:31 +00003403 return TagD;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003404}
3405
John McCall1d7c5282009-12-18 10:40:03 +00003406/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00003407/// check if there's an existing declaration that can't be overloaded.
3408///
3409/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00003410static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3411 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00003412 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00003413 DeclarationName Name,
3414 SourceLocation NameLoc,
3415 unsigned diagnostic) {
3416 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3417 Sema::ForRedeclaration);
3418 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00003419
John McCall1d7c5282009-12-18 10:40:03 +00003420 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00003421 return false;
3422
3423 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00003424 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidis2b642392010-09-23 14:26:01 +00003425 assert(PrevDecl && "Expected a non-null Decl");
3426
3427 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3428 return false;
John McCall68263142009-11-18 22:49:29 +00003429
John McCall1d7c5282009-12-18 10:40:03 +00003430 SemaRef.Diag(NameLoc, diagnostic) << Name;
3431 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00003432
3433 return true;
3434}
3435
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003436/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3437/// anonymous struct or union AnonRecord into the owning context Owner
3438/// and scope S. This routine will be invoked just after we realize
3439/// that an unnamed union or struct is actually an anonymous union or
3440/// struct, e.g.,
3441///
3442/// @code
3443/// union {
3444/// int i;
3445/// float f;
3446/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3447/// // f into the surrounding scope.x
3448/// @endcode
3449///
3450/// This routine is recursive, injecting the names of nested anonymous
3451/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00003452static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper6b9240e2013-07-05 19:34:19 +00003453 DeclContext *Owner,
3454 RecordDecl *AnonRecord,
3455 AccessSpecifier AS,
3456 SmallVectorImpl<NamedDecl *> &Chaining,
3457 bool MSAnonStruct) {
John McCall68263142009-11-18 22:49:29 +00003458 unsigned diagKind
3459 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3460 : diag::err_anonymous_struct_member_redecl;
3461
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003462 bool Invalid = false;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003463
3464 // Look every FieldDecl and IndirectFieldDecl with a name.
3465 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3466 DEnd = AnonRecord->decls_end();
3467 D != DEnd; ++D) {
3468 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3469 cast<NamedDecl>(*D)->getDeclName()) {
3470 ValueDecl *VD = cast<ValueDecl>(*D);
3471 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3472 VD->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003473 // C++ [class.union]p2:
3474 // The names of the members of an anonymous union shall be
3475 // distinct from the names of any other entity in the
3476 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003477 Invalid = true;
3478 } else {
3479 // C++ [class.union]p2:
3480 // For the purpose of name lookup, after the anonymous union
3481 // definition, the members of the anonymous union are
3482 // considered to have been defined in the scope in which the
3483 // anonymous union is declared.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003484 unsigned OldChainingSize = Chaining.size();
3485 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3486 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3487 PE = IF->chain_end(); PI != PE; ++PI)
3488 Chaining.push_back(*PI);
3489 else
3490 Chaining.push_back(VD);
3491
Francois Pichet87c2e122010-11-21 06:08:52 +00003492 assert(Chaining.size() >= 2);
3493 NamedDecl **NamedChain =
3494 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3495 for (unsigned i = 0; i < Chaining.size(); i++)
3496 NamedChain[i] = Chaining[i];
3497
3498 IndirectFieldDecl* IndirectField =
Francois Pichet8e161ed2010-11-23 06:07:27 +00003499 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3500 VD->getIdentifier(), VD->getType(),
Francois Pichet87c2e122010-11-21 06:08:52 +00003501 NamedChain, Chaining.size());
3502
3503 IndirectField->setAccess(AS);
3504 IndirectField->setImplicit();
3505 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallaec03712010-05-21 20:45:30 +00003506
3507 // That includes picking up the appropriate access specifier.
Francois Pichet8e161ed2010-11-23 06:07:27 +00003508 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet87c2e122010-11-21 06:08:52 +00003509
Francois Pichet8e161ed2010-11-23 06:07:27 +00003510 Chaining.resize(OldChainingSize);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003511 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003512 }
3513 }
3514
3515 return Invalid;
3516}
3517
Douglas Gregor16573fa2010-04-19 22:54:31 +00003518/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3519/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCalld931b082010-08-26 03:08:43 +00003520/// illegal input values are mapped to SC_None.
3521static StorageClass
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003522StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3523 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3524 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3525 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregor16573fa2010-04-19 22:54:31 +00003526 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00003527 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003528 case DeclSpec::SCS_extern:
3529 if (DS.isExternInLinkageSpec())
3530 return SC_None;
3531 return SC_Extern;
John McCalld931b082010-08-26 03:08:43 +00003532 case DeclSpec::SCS_static: return SC_Static;
3533 case DeclSpec::SCS_auto: return SC_Auto;
3534 case DeclSpec::SCS_register: return SC_Register;
3535 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003536 // Illegal SCSs map to None: error reporting is up to the caller.
3537 case DeclSpec::SCS_mutable: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00003538 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00003539 }
3540 llvm_unreachable("unknown storage class specifier");
3541}
3542
Francois Pichet8e161ed2010-11-23 06:07:27 +00003543/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003544/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgacbabf12012-02-03 15:47:04 +00003545/// (C++ [class.union]) and a C11 feature; anonymous structures
3546/// are a C11 feature and GNU C++ extension.
John McCalld226f652010-08-21 09:40:31 +00003547Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3548 AccessSpecifier AS,
3549 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003550 DeclContext *Owner = Record->getDeclContext();
3551
3552 // Diagnose whether this anonymous struct/union is an extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00003553 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003554 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikie4e4d0842012-03-11 07:00:24 +00003555 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003556 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikie4e4d0842012-03-11 07:00:24 +00003557 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgacbabf12012-02-03 15:47:04 +00003558 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00003559
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003560 // C and C++ require different kinds of checks for anonymous
3561 // structs/unions.
3562 bool Invalid = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00003563 if (getLangOpts().CPlusPlus) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003564 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00003565 unsigned DiagID;
David Blaikie2b79c322011-10-19 22:43:29 +00003566 if (Record->isUnion()) {
3567 // C++ [class.union]p6:
3568 // Anonymous unions declared in a named namespace or in the
3569 // global namespace shall be declared static.
3570 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3571 (isa<TranslationUnitDecl>(Owner) ||
3572 (isa<NamespaceDecl>(Owner) &&
3573 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie82c8ca12011-10-20 02:49:08 +00003574 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3575 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie2b79c322011-10-19 22:43:29 +00003576
3577 // Recover by adding 'static'.
3578 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3579 PrevSpec, DiagID);
3580 }
3581 // C++ [class.union]p6:
3582 // A storage class is not allowed in a declaration of an
3583 // anonymous union in a class scope.
3584 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3585 isa<RecordDecl>(Owner)) {
3586 Diag(DS.getStorageClassSpecLoc(),
David Blaikief6f876c2011-10-20 02:10:55 +00003587 diag::err_anonymous_union_with_storage_spec)
3588 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie2b79c322011-10-19 22:43:29 +00003589
3590 // Recover by removing the storage specifier.
David Blaikied662a792011-10-19 22:56:21 +00003591 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3592 SourceLocation(),
David Blaikie2b79c322011-10-19 22:43:29 +00003593 PrevSpec, DiagID);
3594 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003595 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003596
Douglas Gregor7604f642011-05-09 23:05:33 +00003597 // Ignore const/volatile/restrict qualifiers.
3598 if (DS.getTypeQualifiers()) {
3599 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3600 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003601 << Record->isUnion() << "const"
Douglas Gregor7604f642011-05-09 23:05:33 +00003602 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3603 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003604 Diag(DS.getVolatileSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003605 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003606 << Record->isUnion() << "volatile"
Douglas Gregor7604f642011-05-09 23:05:33 +00003607 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3608 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003609 Diag(DS.getRestrictSpecLoc(),
David Blaikied662a792011-10-19 22:56:21 +00003610 diag::ext_anonymous_struct_union_qualified)
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003611 << Record->isUnion() << "restrict"
Douglas Gregor7604f642011-05-09 23:05:33 +00003612 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith4cf4a5e2013-03-28 01:55:44 +00003613 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3614 Diag(DS.getAtomicSpecLoc(),
3615 diag::ext_anonymous_struct_union_qualified)
3616 << Record->isUnion() << "_Atomic"
3617 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor7604f642011-05-09 23:05:33 +00003618
3619 DS.ClearTypeQualifiers();
3620 }
3621
Mike Stump1eb44332009-09-09 15:08:12 +00003622 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003623 // The member-specification of an anonymous union shall only
3624 // define non-static data members. [Note: nested types and
3625 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003626 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3627 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003628 Mem != MemEnd; ++Mem) {
3629 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3630 // C++ [class.union]p3:
3631 // An anonymous union shall not have private or protected
3632 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00003633 assert(FD->getAccess() != AS_none);
3634 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003635 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3636 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3637 Invalid = true;
3638 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003639
Sean Huntcf34e752011-05-16 22:41:40 +00003640 // C++ [class.union]p1
3641 // An object of a class with a non-trivial constructor, a non-trivial
3642 // copy constructor, a non-trivial destructor, or a non-trivial copy
3643 // assignment operator cannot be a member of a union, nor can an
3644 // array of such objects.
Richard Smithe7d7c392011-10-19 20:41:51 +00003645 if (CheckNontrivialField(FD))
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00003646 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003647 } else if ((*Mem)->isImplicit()) {
3648 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00003649 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3650 // This is a type that showed up in an
3651 // elaborated-type-specifier inside the anonymous struct or
3652 // union, but which actually declares a type outside of the
3653 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003654 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3655 if (!MemRecord->isAnonymousStructOrUnion() &&
3656 MemRecord->getDeclName()) {
Francois Pichet538e0d02010-09-08 11:32:25 +00003657 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003658 if (getLangOpts().MicrosoftExt)
Francois Pichet538e0d02010-09-08 11:32:25 +00003659 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3660 << (int)Record->isUnion();
3661 else {
3662 // This is a nested type declaration.
3663 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3664 << (int)Record->isUnion();
3665 Invalid = true;
3666 }
Richard Smithc5f7d6a2013-01-28 00:54:05 +00003667 } else {
3668 // This is an anonymous type definition within another anonymous type.
3669 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3670 // not part of standard C++.
3671 Diag(MemRecord->getLocation(),
Richard Smithf2705192013-01-31 03:11:12 +00003672 diag::ext_anonymous_record_with_anonymous_type)
3673 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003674 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00003675 } else if (isa<AccessSpecDecl>(*Mem)) {
3676 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003677 } else {
3678 // We have something that isn't a non-static data
3679 // member. Complain about it.
3680 unsigned DK = diag::err_anonymous_record_bad_member;
3681 if (isa<TypeDecl>(*Mem))
3682 DK = diag::err_anonymous_record_with_type;
3683 else if (isa<FunctionDecl>(*Mem))
3684 DK = diag::err_anonymous_record_with_function;
3685 else if (isa<VarDecl>(*Mem))
3686 DK = diag::err_anonymous_record_with_static;
Francois Pichet538e0d02010-09-08 11:32:25 +00003687
3688 // Visual C++ allows type definition in anonymous struct or union.
David Blaikie4e4d0842012-03-11 07:00:24 +00003689 if (getLangOpts().MicrosoftExt &&
Francois Pichet538e0d02010-09-08 11:32:25 +00003690 DK == diag::err_anonymous_record_with_type)
3691 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003692 << (int)Record->isUnion();
Francois Pichet538e0d02010-09-08 11:32:25 +00003693 else {
3694 Diag((*Mem)->getLocation(), DK)
3695 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003696 Invalid = true;
Francois Pichet538e0d02010-09-08 11:32:25 +00003697 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003698 }
3699 }
Mike Stump1eb44332009-09-09 15:08:12 +00003700 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003701
3702 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003703 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikie4e4d0842012-03-11 07:00:24 +00003704 << (int)getLangOpts().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003705 Invalid = true;
3706 }
3707
John McCalleb692e02009-10-22 23:31:08 +00003708 // Mock up a declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003709 Declarator Dc(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00003710 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00003711 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00003712
Mike Stump1eb44332009-09-09 15:08:12 +00003713 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003714 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003715 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003716 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003717 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003718 Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003719 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003720 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00003721 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003722 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003723 /*InitStyle=*/ICIS_NoInit);
John McCallaec03712010-05-21 20:45:30 +00003724 Anon->setAccess(AS);
David Blaikie4e4d0842012-03-11 07:00:24 +00003725 if (getLangOpts().CPlusPlus)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003726 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003727 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00003728 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00003729 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003730 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003731 // mutable can only appear on non-static class members, so it's always
3732 // an error here
3733 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3734 Invalid = true;
John McCalld931b082010-08-26 03:08:43 +00003735 SC = SC_None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003736 }
3737
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003738 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar96a00142012-03-09 18:35:03 +00003739 DS.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003740 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003741 Context.getTypeDeclType(Record),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003742 TInfo, SC);
Richard Smith16ee8192011-09-18 00:06:34 +00003743
3744 // Default-initialize the implicit variable. This initialization will be
3745 // trivial in almost all cases, except if a union member has an in-class
3746 // initializer:
3747 // union { int n = 0; };
3748 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003749 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003750 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003751
3752 // Add the anonymous struct/union object to the current
3753 // context. We'll be referencing this object when we refer to one of
3754 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003755 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00003756
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003757 // Inject the members of the anonymous struct/union into the owning
3758 // context and into the identifier resolver chain for name lookup
3759 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003760 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet87c2e122010-11-21 06:08:52 +00003761 Chain.push_back(Anon);
3762
Francois Pichet8e161ed2010-11-23 06:07:27 +00003763 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3764 Chain, false))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003765 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003766
3767 // Mark this as an anonymous struct/union type. Note that we do not
3768 // do this until after we have already checked and injected the
3769 // members of this anonymous struct/union type, because otherwise
3770 // the members could be injected twice: once by DeclContext when it
3771 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00003772 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003773 Record->setAnonymousStructOrUnion(true);
3774
3775 if (Invalid)
3776 Anon->setInvalidDecl();
3777
John McCalld226f652010-08-21 09:40:31 +00003778 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003779}
3780
Francois Pichet8e161ed2010-11-23 06:07:27 +00003781/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3782/// Microsoft C anonymous structure.
3783/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3784/// Example:
3785///
3786/// struct A { int a; };
3787/// struct B { struct A; int b; };
3788///
3789/// void foo() {
3790/// B var;
3791/// var.a = 3;
3792/// }
3793///
3794Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3795 RecordDecl *Record) {
3796
3797 // If there is no Record, get the record via the typedef.
3798 if (!Record)
3799 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3800
3801 // Mock up a declarator.
3802 Declarator Dc(DS, Declarator::TypeNameContext);
3803 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3804 assert(TInfo && "couldn't build declarator info for anonymous struct");
3805
3806 // Create a declaration for this anonymous struct.
3807 NamedDecl* Anon = FieldDecl::Create(Context,
3808 cast<RecordDecl>(CurContext),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003809 DS.getLocStart(),
3810 DS.getLocStart(),
Francois Pichet8e161ed2010-11-23 06:07:27 +00003811 /*IdentifierInfo=*/0,
3812 Context.getTypeDeclType(Record),
3813 TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00003814 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003815 /*InitStyle=*/ICIS_NoInit);
Francois Pichet8e161ed2010-11-23 06:07:27 +00003816 Anon->setImplicit();
3817
3818 // Add the anonymous struct object to the current context.
3819 CurContext->addDecl(Anon);
3820
3821 // Inject the members of the anonymous struct into the current
3822 // context and into the identifier resolver chain for name lookup
3823 // purposes.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003824 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet8e161ed2010-11-23 06:07:27 +00003825 Chain.push_back(Anon);
3826
Nico Weberee625af2012-02-01 00:41:00 +00003827 RecordDecl *RecordDef = Record->getDefinition();
3828 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3829 RecordDef, AS_none,
3830 Chain, true))
Francois Pichet8e161ed2010-11-23 06:07:27 +00003831 Anon->setInvalidDecl();
3832
3833 return Anon;
3834}
Steve Narofff0090632007-09-02 02:04:30 +00003835
Douglas Gregor10bd3682008-11-17 22:58:34 +00003836/// GetNameForDeclarator - Determine the full declaration name for the
3837/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00003838DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00003839 return GetNameFromUnqualifiedId(D.getName());
3840}
3841
Abramo Bagnara25777432010-08-11 22:01:17 +00003842/// \brief Retrieves the declaration name from a parsed unqualified-id.
3843DeclarationNameInfo
3844Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3845 DeclarationNameInfo NameInfo;
3846 NameInfo.setLoc(Name.StartLocation);
3847
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003848 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00003849
Fariborz Jahanian98a54032011-07-12 17:16:56 +00003850 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnara25777432010-08-11 22:01:17 +00003851 case UnqualifiedId::IK_Identifier:
3852 NameInfo.setName(Name.Identifier);
3853 NameInfo.setLoc(Name.StartLocation);
3854 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00003855
Abramo Bagnara25777432010-08-11 22:01:17 +00003856 case UnqualifiedId::IK_OperatorFunctionId:
3857 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3858 Name.OperatorFunctionId.Operator));
3859 NameInfo.setLoc(Name.StartLocation);
3860 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3861 = Name.OperatorFunctionId.SymbolLocations[0];
3862 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3863 = Name.EndLocation.getRawEncoding();
3864 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003865
Abramo Bagnara25777432010-08-11 22:01:17 +00003866 case UnqualifiedId::IK_LiteralOperatorId:
3867 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3868 Name.Identifier));
3869 NameInfo.setLoc(Name.StartLocation);
3870 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3871 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003872
Abramo Bagnara25777432010-08-11 22:01:17 +00003873 case UnqualifiedId::IK_ConversionFunctionId: {
3874 TypeSourceInfo *TInfo;
3875 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3876 if (Ty.isNull())
3877 return DeclarationNameInfo();
3878 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3879 Context.getCanonicalType(Ty)));
3880 NameInfo.setLoc(Name.StartLocation);
3881 NameInfo.setNamedTypeInfo(TInfo);
3882 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00003883 }
Abramo Bagnara25777432010-08-11 22:01:17 +00003884
3885 case UnqualifiedId::IK_ConstructorName: {
3886 TypeSourceInfo *TInfo;
3887 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3888 if (Ty.isNull())
3889 return DeclarationNameInfo();
3890 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3891 Context.getCanonicalType(Ty)));
3892 NameInfo.setLoc(Name.StartLocation);
3893 NameInfo.setNamedTypeInfo(TInfo);
3894 return NameInfo;
3895 }
3896
3897 case UnqualifiedId::IK_ConstructorTemplateId: {
3898 // In well-formed code, we can only have a constructor
3899 // template-id that refers to the current context, so go there
3900 // to find the actual type being constructed.
3901 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3902 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3903 return DeclarationNameInfo();
3904
3905 // Determine the type of the class being constructed.
3906 QualType CurClassType = Context.getTypeDeclType(CurClass);
3907
3908 // FIXME: Check two things: that the template-id names the same type as
3909 // CurClassType, and that the template-id does not occur when the name
3910 // was qualified.
3911
3912 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3913 Context.getCanonicalType(CurClassType)));
3914 NameInfo.setLoc(Name.StartLocation);
3915 // FIXME: should we retrieve TypeSourceInfo?
3916 NameInfo.setNamedTypeInfo(0);
3917 return NameInfo;
3918 }
3919
3920 case UnqualifiedId::IK_DestructorName: {
3921 TypeSourceInfo *TInfo;
3922 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3923 if (Ty.isNull())
3924 return DeclarationNameInfo();
3925 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3926 Context.getCanonicalType(Ty)));
3927 NameInfo.setLoc(Name.StartLocation);
3928 NameInfo.setNamedTypeInfo(TInfo);
3929 return NameInfo;
3930 }
3931
3932 case UnqualifiedId::IK_TemplateId: {
John McCall2b5289b2010-08-23 07:28:44 +00003933 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00003934 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3935 return Context.getNameForTemplate(TName, TNameLoc);
3936 }
3937
3938 } // switch (Name.getKind())
3939
David Blaikieb219cfc2011-09-23 05:06:16 +00003940 llvm_unreachable("Unknown name kind");
Douglas Gregor10bd3682008-11-17 22:58:34 +00003941}
3942
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003943static QualType getCoreType(QualType Ty) {
3944 do {
3945 if (Ty->isPointerType() || Ty->isReferenceType())
3946 Ty = Ty->getPointeeType();
3947 else if (Ty->isArrayType())
3948 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3949 else
3950 return Ty.withoutLocalFastQualifiers();
3951 } while (true);
3952}
3953
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00003954/// hasSimilarParameters - Determine whether the C++ functions Declaration
3955/// and Definition have "nearly" matching parameters. This heuristic is
3956/// used to improve diagnostics in the case where an out-of-line function
3957/// definition doesn't match any declaration within the class or namespace.
3958/// Also sets Params to the list of indices to the parameters that differ
3959/// between the declaration and the definition. If hasSimilarParameters
3960/// returns true and Params is empty, then all of the parameters match.
3961static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003962 FunctionDecl *Declaration,
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003963 FunctionDecl *Definition,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003964 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003965 Params.clear();
Douglas Gregor584049d2008-12-15 23:53:10 +00003966 if (Declaration->param_size() != Definition->param_size())
3967 return false;
3968 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3969 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3970 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3971
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003972 // The parameter types are identical
Matt Beaumont-Gay903d6dc2011-08-23 01:35:51 +00003973 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00003974 continue;
3975
3976 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3977 QualType DefParamBaseTy = getCoreType(DefParamTy);
3978 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3979 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3980
3981 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3982 (DeclTyName && DeclTyName == DefTyName))
3983 Params.push_back(Idx);
3984 else // The two parameters aren't even close
Douglas Gregor584049d2008-12-15 23:53:10 +00003985 return false;
3986 }
3987
3988 return true;
3989}
3990
John McCall63b43852010-04-29 23:50:39 +00003991/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3992/// declarator needs to be rebuilt in the current instantiation.
3993/// Any bits of declarator which appear before the name are valid for
3994/// consideration here. That's specifically the type in the decl spec
3995/// and the base type in any member-pointer chunks.
3996static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3997 DeclarationName Name) {
3998 // The types we specifically need to rebuild are:
3999 // - typenames, typeofs, and decltypes
4000 // - types which will become injected class names
4001 // Of course, we also need to rebuild any type referencing such a
4002 // type. It's safest to just say "dependent", but we call out a
4003 // few cases here.
4004
4005 DeclSpec &DS = D.getMutableDeclSpec();
4006 switch (DS.getTypeSpecType()) {
4007 case DeclSpec::TST_typename:
4008 case DeclSpec::TST_typeofType:
Eli Friedmanb001de72011-10-06 23:00:33 +00004009 case DeclSpec::TST_underlyingType:
4010 case DeclSpec::TST_atomic: {
John McCall63b43852010-04-29 23:50:39 +00004011 // Grab the type from the parser.
4012 TypeSourceInfo *TSI = 0;
John McCallb3d87482010-08-24 05:47:05 +00004013 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall63b43852010-04-29 23:50:39 +00004014 if (T.isNull() || !T->isDependentType()) break;
4015
4016 // Make sure there's a type source info. This isn't really much
4017 // of a waste; most dependent types should have type source info
4018 // attached already.
4019 if (!TSI)
4020 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4021
4022 // Rebuild the type in the current instantiation.
4023 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4024 if (!TSI) return true;
4025
4026 // Store the new type back in the decl spec.
John McCallb3d87482010-08-24 05:47:05 +00004027 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4028 DS.UpdateTypeRep(LocType);
4029 break;
4030 }
4031
Richard Smithc4a83912012-10-01 20:35:07 +00004032 case DeclSpec::TST_decltype:
John McCallb3d87482010-08-24 05:47:05 +00004033 case DeclSpec::TST_typeofExpr: {
4034 Expr *E = DS.getRepAsExpr();
John McCall60d7b3a2010-08-24 06:29:42 +00004035 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallb3d87482010-08-24 05:47:05 +00004036 if (Result.isInvalid()) return true;
4037 DS.UpdateExprRep(Result.get());
John McCall63b43852010-04-29 23:50:39 +00004038 break;
4039 }
4040
4041 default:
4042 // Nothing to do for these decl specs.
4043 break;
4044 }
4045
4046 // It doesn't matter what order we do this in.
4047 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4048 DeclaratorChunk &Chunk = D.getTypeObject(I);
4049
4050 // The only type information in the declarator which can come
4051 // before the declaration name is the base type of a member
4052 // pointer.
4053 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4054 continue;
4055
4056 // Rebuild the scope specifier in-place.
4057 CXXScopeSpec &SS = Chunk.Mem.Scope();
4058 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4059 return true;
4060 }
4061
4062 return false;
4063}
4064
Anders Carlsson3242ee02011-07-04 16:28:17 +00004065Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00004066 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004067 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004068
4069 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregore7be1092012-04-30 18:13:01 +00004070 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00004071 Dcl->setTopLevelDeclInObjCContainer();
4072
4073 return Dcl;
John McCall7cd088e2010-08-24 07:21:54 +00004074}
4075
Richard Smith162e1c12011-04-15 14:24:37 +00004076/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4077/// If T is the name of a class, then each of the following shall have a
4078/// name different from T:
4079/// - every static data member of class T;
4080/// - every member function of class T
4081/// - every member of class T that is itself a type;
4082/// \returns true if the declaration name violates these rules.
4083bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4084 DeclarationNameInfo NameInfo) {
4085 DeclarationName Name = NameInfo.getName();
4086
4087 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4088 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4089 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4090 return true;
4091 }
4092
4093 return false;
4094}
Douglas Gregor42acead2012-03-17 23:06:31 +00004095
Douglas Gregor69605872012-03-28 16:01:27 +00004096/// \brief Diagnose a declaration whose declarator-id has the given
4097/// nested-name-specifier.
4098///
4099/// \param SS The nested-name-specifier of the declarator-id.
4100///
4101/// \param DC The declaration context to which the nested-name-specifier
4102/// resolves.
4103///
4104/// \param Name The name of the entity being declared.
4105///
4106/// \param Loc The location of the name of the entity being declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004107///
4108/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregor69605872012-03-28 16:01:27 +00004109bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor42acead2012-03-17 23:06:31 +00004110 DeclarationName Name,
Douglas Gregor69605872012-03-28 16:01:27 +00004111 SourceLocation Loc) {
4112 DeclContext *Cur = CurContext;
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004113 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregor69605872012-03-28 16:01:27 +00004114 Cur = Cur->getParent();
4115
4116 // C++ [dcl.meaning]p1:
4117 // A declarator-id shall not be qualified except for the definition
4118 // of a member function (9.3) or static data member (9.4) outside of
4119 // its class, the definition or explicit instantiation of a function
4120 // or variable member of a namespace outside of its namespace, or the
4121 // definition of an explicit specialization outside of its namespace,
4122 // or the declaration of a friend function that is a member of
4123 // another class or namespace (11.3). [...]
4124
4125 // The user provided a superfluous scope specifier that refers back to the
4126 // class or namespaces in which the entity is already declared.
Douglas Gregor42acead2012-03-17 23:06:31 +00004127 //
4128 // class X {
4129 // void X::f();
4130 // };
Douglas Gregor69605872012-03-28 16:01:27 +00004131 if (Cur->Equals(DC)) {
Douglas Gregor75379452012-09-13 20:16:20 +00004132 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4133 : diag::err_member_extra_qualification)
Douglas Gregor42acead2012-03-17 23:06:31 +00004134 << Name << FixItHint::CreateRemoval(SS.getRange());
4135 SS.clear();
4136 return false;
4137 }
Douglas Gregor69605872012-03-28 16:01:27 +00004138
4139 // Check whether the qualifying scope encloses the scope of the original
4140 // declaration.
4141 if (!Cur->Encloses(DC)) {
4142 if (Cur->isRecord())
4143 Diag(Loc, diag::err_member_qualification)
4144 << Name << SS.getRange();
4145 else if (isa<TranslationUnitDecl>(DC))
4146 Diag(Loc, diag::err_invalid_declarator_global_scope)
4147 << Name << SS.getRange();
4148 else if (isa<FunctionDecl>(Cur))
4149 Diag(Loc, diag::err_invalid_declarator_in_function)
4150 << Name << SS.getRange();
Eli Friedmana03c5ee2013-08-12 21:54:01 +00004151 else if (isa<BlockDecl>(Cur))
4152 Diag(Loc, diag::err_invalid_declarator_in_block)
4153 << Name << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004154 else
4155 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smitha1c4f7c2012-04-13 04:07:40 +00004156 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregor69605872012-03-28 16:01:27 +00004157
Douglas Gregor42acead2012-03-17 23:06:31 +00004158 return true;
Douglas Gregor69605872012-03-28 16:01:27 +00004159 }
4160
4161 if (Cur->isRecord()) {
4162 // Cannot qualify members within a class.
4163 Diag(Loc, diag::err_member_qualification)
4164 << Name << SS.getRange();
4165 SS.clear();
4166
4167 // C++ constructors and destructors with incorrect scopes can break
4168 // our AST invariants by having the wrong underlying types. If
4169 // that's the case, then drop this declaration entirely.
4170 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4171 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4172 !Context.hasSameType(Name.getCXXNameType(),
4173 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4174 return true;
4175
4176 return false;
4177 }
Douglas Gregor42acead2012-03-17 23:06:31 +00004178
Douglas Gregor69605872012-03-28 16:01:27 +00004179 // C++11 [dcl.meaning]p1:
4180 // [...] "The nested-name-specifier of the qualified declarator-id shall
4181 // not begin with a decltype-specifer"
4182 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4183 while (SpecLoc.getPrefix())
4184 SpecLoc = SpecLoc.getPrefix();
4185 if (dyn_cast_or_null<DecltypeType>(
4186 SpecLoc.getNestedNameSpecifier()->getAsType()))
4187 Diag(Loc, diag::err_decltype_in_declarator)
4188 << SpecLoc.getTypeLoc().getSourceRange();
4189
Douglas Gregor42acead2012-03-17 23:06:31 +00004190 return false;
4191}
4192
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00004193NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4194 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnara25777432010-08-11 22:01:17 +00004195 // TODO: consider using NameInfo for diagnostic.
4196 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4197 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00004198
Chris Lattnere80a59c2007-07-25 00:24:17 +00004199 // All of these full declarators require an identifier. If it doesn't have
4200 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00004201 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00004202 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar96a00142012-03-09 18:35:03 +00004203 Diag(D.getDeclSpec().getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004204 diag::err_declarator_need_ident)
4205 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00004206 return 0;
Douglas Gregor56c04582010-12-16 00:46:58 +00004207 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4208 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004209
Chris Lattner31e05722007-08-26 06:24:45 +00004210 // The scope passed in may not be a decl scope. Zip up the scope tree until
4211 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00004212 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00004213 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00004214 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004215
John McCall63b43852010-04-29 23:50:39 +00004216 DeclContext *DC = CurContext;
4217 if (D.getCXXScopeSpec().isInvalid())
4218 D.setInvalidType();
4219 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6ccab972010-12-16 01:14:37 +00004220 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4221 UPPC_DeclarationQualifier))
4222 return 0;
4223
John McCall63b43852010-04-29 23:50:39 +00004224 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4225 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4226 if (!DC) {
4227 // If we could not compute the declaration context, it's because the
4228 // declaration context is dependent but does not refer to a class,
4229 // class template, or class template partial specialization. Complain
4230 // and return early, to avoid the coming semantic disaster.
4231 Diag(D.getIdentifierLoc(),
4232 diag::err_template_qualified_declarator_no_match)
4233 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4234 << D.getCXXScopeSpec().getRange();
John McCalld226f652010-08-21 09:40:31 +00004235 return 0;
John McCall63b43852010-04-29 23:50:39 +00004236 }
John McCall63b43852010-04-29 23:50:39 +00004237 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00004238
John McCall63b43852010-04-29 23:50:39 +00004239 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00004240 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCalld226f652010-08-21 09:40:31 +00004241 return 0;
John McCall63b43852010-04-29 23:50:39 +00004242
Douglas Gregor69605872012-03-28 16:01:27 +00004243 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4244 Diag(D.getIdentifierLoc(),
4245 diag::err_member_def_undefined_record)
4246 << Name << DC << D.getCXXScopeSpec().getRange();
4247 D.setInvalidType();
4248 } else if (!D.getDeclSpec().isFriendSpecified()) {
4249 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4250 Name, D.getIdentifierLoc())) {
4251 if (DC->isRecord())
Douglas Gregor42acead2012-03-17 23:06:31 +00004252 return 0;
Douglas Gregor69605872012-03-28 16:01:27 +00004253
4254 D.setInvalidType();
Douglas Gregor922fff22010-10-13 22:19:53 +00004255 }
John McCall63b43852010-04-29 23:50:39 +00004256 }
4257
4258 // Check whether we need to rebuild the type of the given
4259 // declaration in the current instantiation.
4260 if (EnteringContext && IsDependentContext &&
4261 TemplateParamLists.size() != 0) {
4262 ContextRAII SavedContext(*this, DC);
4263 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4264 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00004265 }
4266 }
Richard Smith162e1c12011-04-15 14:24:37 +00004267
4268 if (DiagnoseClassNameShadow(DC, NameInfo))
4269 // If this is a typedef, we'll end up spewing multiple diagnostics.
4270 // Just return early; it's safer.
4271 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4272 return 0;
Douglas Gregora6e937c2010-10-15 13:21:21 +00004273
John McCallbf1a0282010-06-04 23:28:52 +00004274 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4275 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004276
Douglas Gregord0937222010-12-13 22:49:22 +00004277 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4278 UPPC_DeclarationType))
4279 D.setInvalidType();
4280
Abramo Bagnara25777432010-08-11 22:01:17 +00004281 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00004282 ForRedeclaration);
4283
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004284 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00004285 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00004286 bool IsLinkageLookup = false;
Richard Smithdd9459f2013-08-13 18:18:50 +00004287 bool CreateBuiltins = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004288
4289 // If the declaration we're planning to build will be a function
4290 // or object with linkage, then look for another declaration with
4291 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smithdd9459f2013-08-13 18:18:50 +00004292 //
4293 // If the declaration we're planning to build will be declared with
4294 // external linkage in the translation unit, create any builtin with
4295 // the same name.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004296 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4297 /* Do nothing*/;
Richard Smithdd9459f2013-08-13 18:18:50 +00004298 else if (CurContext->isFunctionOrMethod() &&
4299 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4300 R->isFunctionType())) {
John McCall68263142009-11-18 22:49:29 +00004301 IsLinkageLookup = true;
Richard Smithdd9459f2013-08-13 18:18:50 +00004302 CreateBuiltins =
4303 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4304 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4305 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4306 CreateBuiltins = true;
John McCall68263142009-11-18 22:49:29 +00004307
4308 if (IsLinkageLookup)
4309 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004310
Richard Smithdd9459f2013-08-13 18:18:50 +00004311 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004312 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00004313 LookupQualifiedName(Previous, DC);
4314
Douglas Gregor69605872012-03-28 16:01:27 +00004315 // C++ [dcl.meaning]p1:
4316 // When the declarator-id is qualified, the declaration shall refer to a
4317 // previously declared member of the class or namespace to which the
4318 // qualifier refers (or, in the case of a namespace, of an element of the
4319 // inline namespace set of that namespace (7.3.1)) or to a specialization
4320 // thereof; [...]
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004321 //
Douglas Gregor69605872012-03-28 16:01:27 +00004322 // Note that we already checked the context above, and that we do not have
4323 // enough information to make sure that Previous contains the declaration
4324 // we want to match. For example, given:
Douglas Gregor584049d2008-12-15 23:53:10 +00004325 //
Douglas Gregor9d350972008-12-12 08:25:50 +00004326 // class X {
4327 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00004328 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00004329 // };
4330 //
Douglas Gregor584049d2008-12-15 23:53:10 +00004331 // void X::f(int) { } // ill-formed
4332 //
Douglas Gregor69605872012-03-28 16:01:27 +00004333 // In this case, Previous will point to the overload set
Douglas Gregor584049d2008-12-15 23:53:10 +00004334 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00004335 // matches.
Douglas Gregor69605872012-03-28 16:01:27 +00004336
4337 // C++ [dcl.meaning]p1:
4338 // [...] the member shall not merely have been introduced by a
4339 // using-declaration in the scope of the class or namespace nominated by
4340 // the nested-name-specifier of the declarator-id.
4341 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00004342 }
4343
John McCall68263142009-11-18 22:49:29 +00004344 if (Previous.isSingleResult() &&
4345 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00004346 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004347 if (!D.isInvalidType())
Douglas Gregorcb8f9512011-10-20 17:58:49 +00004348 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4349 Previous.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Douglas Gregor72c3f312008-12-05 18:15:24 +00004351 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00004352 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00004353 }
4354
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004355 // In C++, the previous declaration we find might be a tag type
4356 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00004357 // tag type. Note that this does does not apply if we're declaring a
4358 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00004359 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00004360 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00004361 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00004362
Richard Smith3cdbbdc2013-03-06 01:37:38 +00004363 // Check that there are no default arguments other than in the parameters
4364 // of a function declaration (C++ only).
4365 if (getLangOpts().CPlusPlus)
4366 CheckExtraCXXDefaultArguments(D);
4367
Nico Webere6bb76c2012-12-23 00:40:46 +00004368 NamedDecl *New;
4369
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004370 bool AddToScope = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00004371 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00004372 if (TemplateParamLists.size()) {
4373 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCalld226f652010-08-21 09:40:31 +00004374 return 0;
Douglas Gregore542c862009-06-23 23:11:28 +00004375 }
Mike Stump1eb44332009-09-09 15:08:12 +00004376
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004377 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004378 } else if (R->isFunctionType()) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004379 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004380 TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004381 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004382 } else {
Larisse Voufoef4579c2013-08-06 01:03:05 +00004383 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4384 AddToScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00004385 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004386
4387 if (New == 0)
John McCalld226f652010-08-21 09:40:31 +00004388 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004390 // If this has an identifier and is not an invalid redeclaration or
4391 // function template specialization, add it to the scope stack.
Francois Pichetaf0f4d02011-08-14 03:52:19 +00004392 if (New->getDeclName() && AddToScope &&
Richard Smitha41c97a2013-09-20 01:15:31 +00004393 !(D.isRedeclaration() && New->isInvalidDecl())) {
4394 // Only make a locally-scoped extern declaration visible if it is the first
4395 // declaration of this entity. Qualified lookup for such an entity should
4396 // only find this declaration if there is no visible declaration of it.
4397 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4398 PushOnScopeChains(New, S, AddToContext);
4399 if (!AddToContext)
4400 CurContext->addHiddenDecl(New);
4401 }
Mike Stump1eb44332009-09-09 15:08:12 +00004402
John McCalld226f652010-08-21 09:40:31 +00004403 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00004404}
4405
Abramo Bagnara88adb982012-11-08 16:27:30 +00004406/// Helper method to turn variable array types into constant array
4407/// types in certain situations which would otherwise be errors (for
4408/// GCC compatibility).
Eli Friedman1ca48132009-02-21 00:44:51 +00004409static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4410 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00004411 bool &SizeIsNegative,
4412 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004413 // This method tries to turn a variable array into a constant
4414 // array even when the size isn't an ICE. This is necessary
4415 // for compatibility with code that depends on gcc's buggy
4416 // constant expression folding, like struct {char x[(int)(char*)2];}
4417 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004418 Oversized = 0;
4419
4420 if (T->isDependentType())
4421 return QualType();
4422
John McCall0953e762009-09-24 19:53:00 +00004423 QualifierCollector Qs;
4424 const Type *Ty = Qs.strip(T);
4425
4426 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004427 QualType Pointee = PTy->getPointeeType();
4428 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00004429 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4430 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00004431 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00004432 FixedType = Context.getPointerType(FixedType);
John McCall49f4e1c2010-12-10 11:01:00 +00004433 return Qs.apply(Context, FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00004434 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004435 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4436 QualType Inner = PTy->getInnerType();
4437 QualType FixedType =
4438 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4439 Oversized);
4440 if (FixedType.isNull()) return FixedType;
4441 FixedType = Context.getParenType(FixedType);
4442 return Qs.apply(Context, FixedType);
4443 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004444
4445 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00004446 if (!VLATy)
4447 return QualType();
4448 // FIXME: We should probably handle this case
4449 if (VLATy->getElementType()->isVariablyModifiedType())
4450 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004451
Richard Smithaa9c3502011-12-07 00:43:50 +00004452 llvm::APSInt Res;
Eli Friedman1ca48132009-02-21 00:44:51 +00004453 if (!VLATy->getSizeExpr() ||
Richard Smithaa9c3502011-12-07 00:43:50 +00004454 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedman1ca48132009-02-21 00:44:51 +00004455 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00004456
Douglas Gregor2767ce22010-08-18 00:39:00 +00004457 // Check whether the array size is negative.
Douglas Gregor2767ce22010-08-18 00:39:00 +00004458 if (Res.isSigned() && Res.isNegative()) {
4459 SizeIsNegative = true;
4460 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004461 }
Eli Friedman1ca48132009-02-21 00:44:51 +00004462
Douglas Gregor2767ce22010-08-18 00:39:00 +00004463 // Check whether the array is too large to be addressed.
4464 unsigned ActiveSizeBits
4465 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4466 Res);
4467 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4468 Oversized = Res;
4469 return QualType();
4470 }
4471
4472 return Context.getConstantArrayType(VLATy->getElementType(),
4473 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00004474}
4475
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004476static void
4477FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie39e6ab42013-02-18 22:06:02 +00004478 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4479 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4480 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4481 DstPTL.getPointeeLoc());
4482 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004483 return;
4484 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004485 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4486 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4487 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4488 DstPTL.getInnerLoc());
4489 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4490 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004491 return;
4492 }
David Blaikie39e6ab42013-02-18 22:06:02 +00004493 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4494 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4495 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4496 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004497 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie39e6ab42013-02-18 22:06:02 +00004498 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4499 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4500 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004501}
4502
Abramo Bagnara88adb982012-11-08 16:27:30 +00004503/// Helper method to turn variable array types into constant array
4504/// types in certain situations which would otherwise be errors (for
4505/// GCC compatibility).
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004506static TypeSourceInfo*
4507TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4508 ASTContext &Context,
4509 bool &SizeIsNegative,
4510 llvm::APSInt &Oversized) {
4511 QualType FixedTy
4512 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4513 SizeIsNegative, Oversized);
4514 if (FixedTy.isNull())
4515 return 0;
4516 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4517 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4518 FixedTInfo->getTypeLoc());
4519 return FixedTInfo;
4520}
4521
Richard Smith5ea6ef42013-01-10 23:43:47 +00004522/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith662f41b2013-06-18 20:15:12 +00004523/// that it can be found later for redeclarations. We include any extern "C"
4524/// declaration that is not visible in the translation unit here, not just
4525/// function-scope declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004526void
Richard Smith662f41b2013-06-18 20:15:12 +00004527Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithaa4bc182013-06-30 09:48:50 +00004528 if (!getLangOpts().CPlusPlus &&
4529 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4530 // Don't need to track declarations in the TU in C.
4531 return;
4532
Douglas Gregor63935192009-03-02 00:19:53 +00004533 // Note that we have a locally-scoped external with this name.
Richard Smithaa4bc182013-06-30 09:48:50 +00004534 // FIXME: There can be multiple such declarations if they are functions marked
4535 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith5ea6ef42013-01-10 23:43:47 +00004536 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor63935192009-03-02 00:19:53 +00004537}
4538
Richard Smith662f41b2013-06-18 20:15:12 +00004539NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregorec12ce22011-07-28 14:20:37 +00004540 if (ExternalSource) {
4541 // Load locally-scoped external decls from the external source.
Richard Smith662f41b2013-06-18 20:15:12 +00004542 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregorec12ce22011-07-28 14:20:37 +00004543 SmallVector<NamedDecl *, 4> Decls;
Richard Smith5ea6ef42013-01-10 23:43:47 +00004544 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregorec12ce22011-07-28 14:20:37 +00004545 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4546 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith5ea6ef42013-01-10 23:43:47 +00004547 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4548 if (Pos == LocallyScopedExternCDecls.end())
4549 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregorec12ce22011-07-28 14:20:37 +00004550 }
4551 }
Richard Smith662f41b2013-06-18 20:15:12 +00004552
4553 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola87bcee82013-10-19 16:55:03 +00004554 return D ? D->getMostRecentDecl() : 0;
Douglas Gregorec12ce22011-07-28 14:20:37 +00004555}
4556
Eli Friedman85a53192009-04-07 19:37:57 +00004557/// \brief Diagnose function specifiers on a declaration of an identifier that
4558/// does not identify a function.
Richard Smithc7f81162013-03-18 22:52:47 +00004559void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman85a53192009-04-07 19:37:57 +00004560 // FIXME: We should probably indicate the identifier in question to avoid
4561 // confusion for constructs like "inline int a(), b;"
Richard Smithc7f81162013-03-18 22:52:47 +00004562 if (DS.isInlineSpecified())
4563 Diag(DS.getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004564 diag::err_inline_non_function);
4565
Richard Smithc7f81162013-03-18 22:52:47 +00004566 if (DS.isVirtualSpecified())
4567 Diag(DS.getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004568 diag::err_virtual_non_function);
4569
Richard Smithc7f81162013-03-18 22:52:47 +00004570 if (DS.isExplicitSpecified())
4571 Diag(DS.getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00004572 diag::err_explicit_non_function);
Richard Smithde03c152013-01-17 22:16:11 +00004573
Richard Smithc7f81162013-03-18 22:52:47 +00004574 if (DS.isNoreturnSpecified())
4575 Diag(DS.getNoreturnSpecLoc(),
Richard Smithde03c152013-01-17 22:16:11 +00004576 diag::err_noreturn_non_function);
Eli Friedman85a53192009-04-07 19:37:57 +00004577}
4578
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004579NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004580Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004581 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004582 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4583 if (D.getCXXScopeSpec().isSet()) {
4584 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4585 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004586 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004587 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00004588 DC = CurContext;
4589 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004590 }
4591
Richard Smithc7f81162013-03-18 22:52:47 +00004592 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +00004593
Richard Smithaf1fc7a2011-08-15 21:04:07 +00004594 if (D.getDeclSpec().isConstexprSpecified())
4595 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4596 << 1;
Eli Friedman63054b32009-04-19 20:27:55 +00004597
Douglas Gregoraef01992010-07-13 06:37:01 +00004598 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4599 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4600 << D.getName().getSourceRange();
4601 return 0;
4602 }
4603
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004604 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004605 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004606
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004607 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004608 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00004609
Richard Smith3e4c6c42011-05-05 21:57:07 +00004610 CheckTypedefForVariablyModifiedType(S, NewTD);
4611
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004612 bool Redeclaration = D.isRedeclaration();
4613 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4614 D.setRedeclaration(Redeclaration);
4615 return ND;
Richard Smith162e1c12011-04-15 14:24:37 +00004616}
4617
Richard Smith3e4c6c42011-05-05 21:57:07 +00004618void
4619Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004620 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4621 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004622 // Note that variably modified types must be fixed before merging the decl so
4623 // that redeclarations will match.
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004624 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4625 QualType T = TInfo->getType();
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004626 if (T->isVariablyModifiedType()) {
John McCall781472f2010-08-25 08:40:02 +00004627 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004628
Chris Lattner38c5ebd2009-04-19 05:21:20 +00004629 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00004630 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00004631 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004632 TypeSourceInfo *FixedTInfo =
4633 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4634 SizeIsNegative,
4635 Oversized);
4636 if (FixedTInfo) {
Richard Smith162e1c12011-04-15 14:24:37 +00004637 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00004638 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedman1ca48132009-02-21 00:44:51 +00004639 } else {
4640 if (SizeIsNegative)
Richard Smith162e1c12011-04-15 14:24:37 +00004641 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00004642 else if (T->isVariableArrayType())
Richard Smith162e1c12011-04-15 14:24:37 +00004643 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00004644 else if (Oversized.getBoolValue())
David Blaikied662a792011-10-19 22:56:21 +00004645 Diag(NewTD->getLocation(), diag::err_array_too_large)
4646 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00004647 else
Richard Smith162e1c12011-04-15 14:24:37 +00004648 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004649 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00004650 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004651 }
4652 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00004653}
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004654
Richard Smith3e4c6c42011-05-05 21:57:07 +00004655
4656/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4657/// declares a typedef-name, either using the 'typedef' type specifier or via
4658/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4659NamedDecl*
4660Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4661 LookupResult &Previous, bool &Redeclaration) {
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004662 // Merge the decl with the existing one if appropriate. If the decl is
4663 // in an outer scope, it isn't the same thing.
Richard Smith3e4c6c42011-05-05 21:57:07 +00004664 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregorcc209452011-03-07 16:54:27 +00004665 /*ExplicitInstantiationOrSpecialization=*/false);
Douglas Gregor7dc80e12013-01-09 00:47:56 +00004666 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004667 if (!Previous.empty()) {
4668 Redeclaration = true;
Richard Smith162e1c12011-04-15 14:24:37 +00004669 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00004670 }
4671
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004672 // If this is the C FILE type, notify the AST context.
4673 if (IdentifierInfo *II = NewTD->getIdentifier())
4674 if (!NewTD->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004675 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stump782fa302009-07-28 02:25:19 +00004676 if (II->isStr("FILE"))
4677 Context.setFILEDecl(NewTD);
4678 else if (II->isStr("jmp_buf"))
4679 Context.setjmp_bufDecl(NewTD);
4680 else if (II->isStr("sigjmp_buf"))
4681 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00004682 else if (II->isStr("ucontext_t"))
4683 Context.setucontext_tDecl(NewTD);
Mike Stump782fa302009-07-28 02:25:19 +00004684 }
4685
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00004686 return NewTD;
4687}
4688
Douglas Gregor8f301052009-02-24 19:23:27 +00004689/// \brief Determines whether the given declaration is an out-of-scope
4690/// previous declaration.
4691///
4692/// This routine should be invoked when name lookup has found a
4693/// previous declaration (PrevDecl) that is not in the scope where a
4694/// new declaration by the same name is being introduced. If the new
4695/// declaration occurs in a local scope, previous declarations with
4696/// linkage may still be considered previous declarations (C99
4697/// 6.2.2p4-5, C++ [basic.link]p6).
4698///
4699/// \param PrevDecl the previous declaration found by name
4700/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00004701///
Douglas Gregor8f301052009-02-24 19:23:27 +00004702/// \param DC the context in which the new declaration is being
4703/// declared.
4704///
4705/// \returns true if PrevDecl is an out-of-scope previous declaration
4706/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00004707static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00004708isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4709 ASTContext &Context) {
4710 if (!PrevDecl)
Sebastian Redl7a126a42010-08-31 00:36:30 +00004711 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004712
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00004713 if (!PrevDecl->hasLinkage())
4714 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004715
David Blaikie4e4d0842012-03-11 07:00:24 +00004716 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor8f301052009-02-24 19:23:27 +00004717 // C++ [basic.link]p6:
4718 // If there is a visible declaration of an entity with linkage
4719 // having the same name and type, ignoring entities declared
4720 // outside the innermost enclosing namespace scope, the block
4721 // scope declaration declares that same entity and receives the
4722 // linkage of the previous declaration.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004723 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor8f301052009-02-24 19:23:27 +00004724 if (!OuterContext->isFunctionOrMethod())
4725 // This rule only applies to block-scope declarations.
4726 return false;
Douglas Gregor757c6002010-08-27 22:55:10 +00004727
4728 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4729 if (PrevOuterContext->isRecord())
4730 // We found a member function: ignore it.
4731 return false;
4732
4733 // Find the innermost enclosing namespace for the new and
4734 // previous declarations.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004735 OuterContext = OuterContext->getEnclosingNamespaceContext();
4736 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump1eb44332009-09-09 15:08:12 +00004737
Douglas Gregor757c6002010-08-27 22:55:10 +00004738 // The previous declaration is in a different namespace, so it
4739 // isn't the same function.
4740 if (!OuterContext->Equals(PrevOuterContext))
4741 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00004742 }
4743
Douglas Gregor8f301052009-02-24 19:23:27 +00004744 return true;
4745}
4746
John McCallb6217662010-03-15 10:12:16 +00004747static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4748 CXXScopeSpec &SS = D.getCXXScopeSpec();
4749 if (!SS.isSet()) return;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00004750 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCallb6217662010-03-15 10:12:16 +00004751}
4752
John McCallf85e1932011-06-15 23:02:42 +00004753bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4754 QualType type = decl->getType();
4755 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4756 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4757 // Various kinds of declaration aren't allowed to be __autoreleasing.
4758 unsigned kind = -1U;
4759 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4760 if (var->hasAttr<BlocksAttr>())
4761 kind = 0; // __block
4762 else if (!var->hasLocalStorage())
4763 kind = 1; // global
4764 } else if (isa<ObjCIvarDecl>(decl)) {
4765 kind = 3; // ivar
4766 } else if (isa<FieldDecl>(decl)) {
4767 kind = 2; // field
4768 }
4769
4770 if (kind != -1U) {
4771 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4772 << kind;
4773 }
4774 } else if (lifetime == Qualifiers::OCL_None) {
4775 // Try to infer lifetime.
4776 if (!type->isObjCLifetimeType())
4777 return false;
4778
4779 lifetime = type->getObjCARCImplicitLifetime();
4780 type = Context.getLifetimeQualifiedType(type, lifetime);
4781 decl->setType(type);
4782 }
4783
4784 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4785 // Thread-local variables cannot have lifetime.
4786 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smith38afbc72013-04-13 02:43:54 +00004787 var->getTLSKind()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004788 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004789 << var->getType();
4790 return true;
4791 }
4792 }
4793
4794 return false;
4795}
4796
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004797static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4798 // 'weak' only applies to declarations with external linkage.
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004799 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004800 if (!ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004801 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4802 ND.dropAttr<WeakAttr>();
4803 }
4804 }
4805 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00004806 if (ND.isExternallyVisible()) {
Rafael Espindola4d8a33b2013-01-16 23:49:06 +00004807 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4808 ND.dropAttr<WeakRefAttr>();
4809 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004810 }
Reid Klecknera7225342013-05-20 14:02:37 +00004811
4812 // 'selectany' only applies to externally visible varable declarations.
4813 // It does not apply to functions.
4814 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4815 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4816 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4817 ND.dropAttr<SelectAnyAttr>();
4818 }
4819 }
Rafael Espindola2a5bb502013-01-16 23:11:15 +00004820}
4821
John McCallb421d922013-04-02 02:48:58 +00004822/// Given that we are within the definition of the given function,
4823/// will that definition behave like C99's 'inline', where the
4824/// definition is discarded except for optimization purposes?
4825static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4826 // Try to avoid calling GetGVALinkageForFunction.
4827
4828 // All cases of this require the 'inline' keyword.
4829 if (!FD->isInlined()) return false;
4830
4831 // This is only possible in C++ with the gnu_inline attribute.
4832 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4833 return false;
4834
4835 // Okay, go ahead and call the relatively-more-expensive function.
4836
4837#ifndef NDEBUG
4838 // AST quite reasonably asserts that it's working on a function
4839 // definition. We don't really have a way to tell it that we're
4840 // currently defining the function, so just lie to it in +Asserts
4841 // builds. This is an awful hack.
4842 FD->setLazyBody(1);
4843#endif
4844
4845 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4846
4847#ifndef NDEBUG
4848 FD->setLazyBody(0);
4849#endif
4850
4851 return isC99Inline;
4852}
4853
Richard Smithaa4bc182013-06-30 09:48:50 +00004854/// Determine whether a variable is extern "C" prior to attaching
4855/// an initializer. We can't just call isExternC() here, because that
4856/// will also compute and cache whether the declaration is externally
4857/// visible, which might change when we attach the initializer.
4858///
4859/// This can only be used if the declaration is known to not be a
4860/// redeclaration of an internal linkage declaration.
4861///
4862/// For instance:
4863///
4864/// auto x = []{};
4865///
4866/// Attaching the initializer here makes this declaration not externally
4867/// visible, because its type has internal linkage.
4868///
4869/// FIXME: This is a hack.
4870template<typename T>
4871static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4872 if (S.getLangOpts().CPlusPlus) {
4873 // In C++, the overloadable attribute negates the effects of extern "C".
4874 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4875 return false;
4876 }
4877 return D->isExternC();
4878}
4879
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004880static bool shouldConsiderLinkage(const VarDecl *VD) {
4881 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4882 if (DC->isFunctionOrMethod())
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004883 return VD->hasExternalStorage();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00004884 if (DC->isFileContext())
4885 return true;
4886 if (DC->isRecord())
4887 return false;
4888 llvm_unreachable("Unexpected context");
4889}
4890
4891static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4892 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4893 if (DC->isFileContext() || DC->isFunctionOrMethod())
4894 return true;
4895 if (DC->isRecord())
4896 return false;
4897 llvm_unreachable("Unexpected context");
4898}
4899
Richard Smitha41c97a2013-09-20 01:15:31 +00004900/// Adjust the \c DeclContext for a function or variable that might be a
4901/// function-local external declaration.
4902bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4903 if (!DC->isFunctionOrMethod())
4904 return false;
4905
4906 // If this is a local extern function or variable declared within a function
4907 // template, don't add it into the enclosing namespace scope until it is
4908 // instantiated; it might have a dependent type right now.
4909 if (DC->isDependentContext())
4910 return true;
4911
4912 // C++11 [basic.link]p7:
4913 // When a block scope declaration of an entity with linkage is not found to
4914 // refer to some other declaration, then that entity is a member of the
4915 // innermost enclosing namespace.
4916 //
4917 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4918 // semantically-enclosing namespace, not a lexically-enclosing one.
4919 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4920 DC = DC->getParent();
4921 return true;
4922}
4923
Larisse Voufoef4579c2013-08-06 01:03:05 +00004924NamedDecl *
Chris Lattner16c5dea2010-10-10 18:16:20 +00004925Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004926 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufoef4579c2013-08-06 01:03:05 +00004927 MultiTemplateParamsArg TemplateParamLists,
4928 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00004929 QualType R = TInfo->getType();
Abramo Bagnara25777432010-08-11 22:01:17 +00004930 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004931
Douglas Gregor16573fa2010-04-19 22:54:31 +00004932 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00004933 VarDecl::StorageClass SC =
4934 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Gouly19dbb202013-01-23 11:56:20 +00004935
Richard Smitha41c97a2013-09-20 01:15:31 +00004936 DeclContext *OriginalDC = DC;
4937 bool IsLocalExternDecl = SC == SC_Extern &&
4938 adjustContextForLocalExternDecl(DC);
4939
Richard Smithdf4cc0a2013-04-15 08:33:22 +00004940 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004941 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4942 // half array type (unless the cl_khr_fp16 extension is enabled).
4943 if (Context.getBaseElementType(R)->isHalfType()) {
4944 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4945 D.setInvalidType();
4946 }
4947 }
4948
Douglas Gregor16573fa2010-04-19 22:54:31 +00004949 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004950 // mutable can only appear on non-static class members, so it's always
4951 // an error here
4952 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004953 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004954 SC = SC_None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004955 }
John McCallb421d922013-04-02 02:48:58 +00004956
Richard Smith9109bf12013-06-17 01:34:01 +00004957 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4958 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4959 D.getDeclSpec().getStorageClassSpecLoc())) {
4960 // In C++11, the 'register' storage class specifier is deprecated.
4961 // Suppress the warning in system macros, it's used in macros in some
4962 // popular C system headers, such as in glibc's htonl() macro.
4963 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4964 diag::warn_deprecated_register)
4965 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4966 }
4967
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004968 IdentifierInfo *II = Name.getAsIdentifierInfo();
4969 if (!II) {
4970 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorb5a01872011-10-09 18:55:59 +00004971 << Name;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004972 return 0;
4973 }
4974
Richard Smithc7f81162013-03-18 22:52:47 +00004975 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor021c3b32009-03-11 23:00:04 +00004976
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00004977 if (!DC->isRecord() && S->getFnParent() == 0) {
4978 // C99 6.9p2: The storage-class specifiers auto and register shall not
4979 // appear in the declaration specifiers in an external declaration.
John McCalld931b082010-08-26 03:08:43 +00004980 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004981 // If this is a register variable with an asm label specified, then this
4982 // is a GNU extension.
John McCalld931b082010-08-26 03:08:43 +00004983 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd4b19d52009-05-12 21:44:00 +00004984 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4985 else
4986 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00004987 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004988 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00004989 }
Richard Smith9109bf12013-06-17 01:34:01 +00004990
David Blaikie4e4d0842012-03-11 07:00:24 +00004991 if (getLangOpts().OpenCL) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004992 // Set up the special work-group-local storage class for variables in the
4993 // OpenCL __local address space.
Rafael Espindola0db661e2012-12-21 01:21:33 +00004994 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00004995 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola0db661e2012-12-21 01:21:33 +00004996 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00004997
Guy Benyei21f18c42013-02-07 10:55:47 +00004998 // OpenCL v1.2 s6.9.b p4:
4999 // The sampler type cannot be used with the __local and __global address
5000 // space qualifiers.
5001 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5002 R.getAddressSpace() == LangAS::opencl_global)) {
5003 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5004 }
5005
Guy Benyeie6b9d802013-01-20 12:31:11 +00005006 // OpenCL 1.2 spec, p6.9 r:
5007 // The event type cannot be used to declare a program scope variable.
5008 // The event type cannot be used with the __local, __constant and __global
5009 // address space qualifiers.
5010 if (R->isEventT()) {
5011 if (S->getParent() == 0) {
5012 Diag(D.getLocStart(), diag::err_event_t_global_var);
5013 D.setInvalidType();
5014 }
5015
5016 if (R.getAddressSpace()) {
5017 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5018 D.setInvalidType();
5019 }
5020 }
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005021 }
5022
Larisse Voufoef4579c2013-08-06 01:03:05 +00005023 bool IsExplicitSpecialization = false;
5024 bool IsVariableTemplateSpecialization = false;
5025 bool IsPartialSpecialization = false;
Larisse Voufo4a919892013-08-14 03:09:19 +00005026 bool IsVariableTemplate = false;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005027 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo567f9172013-08-22 00:59:14 +00005028 VarDecl *NewVD = 0;
5029 VarTemplateDecl *NewTemplate = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00005030 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005031 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005032 D.getIdentifierLoc(), II,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005033 R, TInfo, SC);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005034
5035 if (D.isInvalidType())
5036 NewVD->setInvalidDecl();
5037 } else {
Larisse Voufo567f9172013-08-22 00:59:14 +00005038 bool Invalid = false;
5039
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005040 if (DC->isRecord() && !CurContext->isRecord()) {
5041 // This is an out-of-line definition of a static data member.
Rafael Espindola3882aed2013-06-19 13:41:54 +00005042 switch (SC) {
5043 case SC_None:
5044 break;
5045 case SC_Static:
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005046 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5047 diag::err_static_out_of_line)
5048 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola3882aed2013-06-19 13:41:54 +00005049 break;
5050 case SC_Auto:
5051 case SC_Register:
5052 case SC_Extern:
5053 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5054 // to names of variables declared in a block or to function parameters.
5055 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5056 // of class members
5057
5058 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5059 diag::err_storage_class_for_static_member)
5060 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5061 break;
5062 case SC_PrivateExtern:
5063 llvm_unreachable("C storage class in c++!");
5064 case SC_OpenCLWorkGroupLocal:
5065 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindolaea4b1112013-04-04 21:21:25 +00005066 }
Larisse Voufo06935f32013-08-06 03:43:07 +00005067 }
5068
Richard Smithb9c64d82012-02-16 20:41:22 +00005069 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005070 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5071 if (RD->isLocalClass())
5072 Diag(D.getIdentifierLoc(),
5073 diag::err_static_data_member_not_allowed_in_local_class)
5074 << Name << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00005075
Richard Smithb9c64d82012-02-16 20:41:22 +00005076 // C++98 [class.union]p1: If a union contains a static data member,
5077 // the program is ill-formed. C++11 drops this restriction.
5078 if (RD->isUnion())
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005079 Diag(D.getIdentifierLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005080 getLangOpts().CPlusPlus11
Richard Smithb9c64d82012-02-16 20:41:22 +00005081 ? diag::warn_cxx98_compat_static_data_member_in_union
5082 : diag::ext_static_data_member_in_union) << Name;
5083 // We conservatively disallow static data members in anonymous structs.
5084 else if (!RD->getDeclName())
5085 Diag(D.getIdentifierLoc(),
5086 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005087 << Name << RD->isUnion();
5088 }
5089 }
5090
Larisse Voufoef4579c2013-08-06 01:03:05 +00005091 NamedDecl *PrevDecl = 0;
5092 if (Previous.begin() != Previous.end())
5093 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5094 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5095
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005096 // Match up the template parameter lists with the scope specifier, then
5097 // determine whether we have a template or a template specialization.
Larisse Voufo567f9172013-08-22 00:59:14 +00005098 TemplateParameterList *TemplateParams =
5099 MatchTemplateParametersToScopeSpecifier(
5100 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5101 D.getCXXScopeSpec(), TemplateParamLists,
5102 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufoef4579c2013-08-06 01:03:05 +00005103 if (TemplateParams) {
5104 if (!TemplateParams->size() &&
5105 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005106 // There is an extraneous 'template<>' for this variable. Complain
5107 // about it, but allow the declaration of the variable.
5108 Diag(TemplateParams->getTemplateLoc(),
5109 diag::err_template_variable_noparams)
5110 << II
5111 << SourceRange(TemplateParams->getTemplateLoc(),
5112 TemplateParams->getRAngleLoc());
Larisse Voufoef4579c2013-08-06 01:03:05 +00005113 } else {
5114 // Only C++1y supports variable templates (N3651).
5115 Diag(D.getIdentifierLoc(),
5116 getLangOpts().CPlusPlus1y
5117 ? diag::warn_cxx11_compat_variable_template
5118 : diag::ext_variable_template);
5119
5120 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5121 // This is an explicit specialization or a partial specialization.
5122 // Check that we can declare a specialization here
5123
5124 IsVariableTemplateSpecialization = true;
5125 IsPartialSpecialization = TemplateParams->size() > 0;
5126
5127 } else { // if (TemplateParams->size() > 0)
Larisse Voufo06935f32013-08-06 03:43:07 +00005128 // This is a template declaration.
Larisse Voufo4a919892013-08-14 03:09:19 +00005129 IsVariableTemplate = true;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005130
5131 // Check that we can declare a template here.
5132 if (CheckTemplateDeclScope(S, TemplateParams))
5133 return 0;
5134
5135 // If there is a previous declaration with the same name, check
5136 // whether this is a valid redeclaration.
5137 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5138 PrevDecl = PrevVarTemplate = 0;
5139
5140 if (PrevVarTemplate) {
5141 // Ensure that the template parameter lists are compatible.
5142 if (!TemplateParameterListsAreEqual(
5143 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5144 /*Complain=*/true, TPL_TemplateMatch))
5145 return 0;
5146 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5147 // Maybe we will complain about the shadowed template parameter.
5148 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5149
5150 // Just pretend that we didn't see the previous declaration.
5151 PrevDecl = 0;
5152 } else if (PrevDecl) {
5153 // C++ [temp]p5:
5154 // ... a template name declared in namespace scope or in class
5155 // scope shall be unique in that scope.
5156 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5157 << Name;
5158 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5159 return 0;
5160 }
5161
5162 // Check the template parameter list of this declaration, possibly
5163 // merging in the template parameter list from the previous variable
5164 // template declaration.
5165 if (CheckTemplateParameterList(
5166 TemplateParams,
5167 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5168 : 0,
5169 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5170 DC->isDependentContext())
5171 ? TPC_ClassTemplateMember
5172 : TPC_VarTemplate))
5173 Invalid = true;
5174
5175 if (D.getCXXScopeSpec().isSet()) {
5176 // If the name of the template was qualified, we must be defining
5177 // the template out-of-line.
5178 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5179 !PrevVarTemplate) {
Richard Smith4e9686b2013-08-09 04:35:01 +00005180 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5181 << Name << DC << /*IsDefinition*/true
5182 << D.getCXXScopeSpec().getRange();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005183 Invalid = true;
5184 }
5185 }
5186 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005187 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00005188 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5189 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5190
5191 // We have encountered something that the user meant to be a
5192 // specialization (because it has explicitly-specified template
5193 // arguments) but that was not introduced with a "template<>" (or had
5194 // too few of them).
5195 // FIXME: Differentiate between attempts for explicit instantiations
5196 // (starting with "template") and the rest.
5197 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5198 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5199 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5200 "template<> ");
5201 IsVariableTemplateSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00005202 }
Mike Stump1eb44332009-09-09 15:08:12 +00005203
Larisse Voufoef4579c2013-08-06 01:03:05 +00005204 if (IsVariableTemplateSpecialization) {
5205 if (!PrevVarTemplate) {
5206 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5207 << IsPartialSpecialization;
5208 return 0;
5209 }
5210
5211 SourceLocation TemplateKWLoc =
5212 TemplateParamLists.size() > 0
5213 ? TemplateParamLists[0]->getTemplateLoc()
5214 : SourceLocation();
5215 DeclResult Res = ActOnVarTemplateSpecialization(
5216 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5217 IsPartialSpecialization);
5218 if (Res.isInvalid())
5219 return 0;
5220 NewVD = cast<VarDecl>(Res.get());
5221 AddToScope = false;
5222 } else
5223 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5224 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedman63054b32009-04-19 20:27:55 +00005225
Larisse Voufo567f9172013-08-22 00:59:14 +00005226 // If this is supposed to be a variable template, create it as such.
5227 if (IsVariableTemplate) {
5228 NewTemplate =
5229 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5230 TemplateParams, NewVD, PrevVarTemplate);
5231 NewVD->setDescribedVarTemplate(NewTemplate);
5232 }
5233
Richard Smith483b9f32011-02-21 20:05:19 +00005234 // If this decl has an auto type in need of deduction, make a note of the
5235 // Decl so we can diagnose uses of it in its own initializer.
Richard Smitha2c36462013-04-26 16:15:35 +00005236 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smith483b9f32011-02-21 20:05:19 +00005237 ParsingInitForAutoVars.insert(NewVD);
Richard Smith34b41d92011-02-20 03:19:35 +00005238
Larisse Voufo567f9172013-08-22 00:59:14 +00005239 if (D.isInvalidType() || Invalid) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005240 NewVD->setInvalidDecl();
Larisse Voufo567f9172013-08-22 00:59:14 +00005241 if (NewTemplate)
5242 NewTemplate->setInvalidDecl();
5243 }
Mike Stump1eb44332009-09-09 15:08:12 +00005244
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005245 SetNestedNameSpecifier(NewVD, D);
John McCallb6217662010-03-15 10:12:16 +00005246
Larisse Voufoef4579c2013-08-06 01:03:05 +00005247 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5248 if (TemplateParams && TemplateParamLists.size() > 1 &&
5249 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5250 NewVD->setTemplateParameterListsInfo(
5251 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5252 } else if (IsVariableTemplateSpecialization ||
5253 (!TemplateParams && TemplateParamLists.size() > 0 &&
5254 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005255 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00005256 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00005257 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005258 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00005259
Richard Smith7ca48502012-02-13 22:16:19 +00005260 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithdd4b3502011-12-25 21:17:58 +00005261 NewVD->setConstexpr(true);
Abramo Bagnara9b934882010-06-12 08:15:14 +00005262 }
5263
Douglas Gregore3895852011-09-12 18:37:38 +00005264 // Set the lexical context. If the declarator has a C++ scope specifier, the
5265 // lexical context will be different from the semantic context.
5266 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo567f9172013-08-22 00:59:14 +00005267 if (NewTemplate)
5268 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregore3895852011-09-12 18:37:38 +00005269
Richard Smitha41c97a2013-09-20 01:15:31 +00005270 if (IsLocalExternDecl)
5271 NewVD->setLocalExternDecl();
5272
Richard Smithec642442013-04-12 22:46:28 +00005273 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005274 if (NewVD->hasLocalStorage()) {
5275 // C++11 [dcl.stc]p4:
5276 // When thread_local is applied to a variable of block scope the
5277 // storage-class-specifier static is implied if it does not appear
5278 // explicitly.
5279 // Core issue: 'static' is not implied if the variable is declared
5280 // 'extern'.
5281 if (SCSpec == DeclSpec::SCS_unspecified &&
5282 TSCS == DeclSpec::TSCS_thread_local &&
5283 DC->isFunctionOrMethod())
5284 NewVD->setTSCSpec(TSCS);
5285 else
5286 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5287 diag::err_thread_non_global)
5288 << DeclSpec::getSpecifierName(TSCS);
5289 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithec642442013-04-12 22:46:28 +00005290 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5291 diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00005292 else
Enea Zaffanelladc173842013-05-04 08:27:07 +00005293 NewVD->setTSCSpec(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00005294 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005295
John McCallb421d922013-04-02 02:48:58 +00005296 // C99 6.7.4p3
5297 // An inline definition of a function with external linkage shall
5298 // not contain a definition of a modifiable object with static or
5299 // thread storage duration...
5300 // We only apply this when the function is required to be defined
5301 // elsewhere, i.e. when the function is not 'extern inline'. Note
5302 // that a local variable with thread storage duration still has to
5303 // be marked 'static'. Also note that it's possible to get these
5304 // semantics in C++ using __attribute__((gnu_inline)).
5305 if (SC == SC_Static && S->getFnParent() != 0 &&
5306 !NewVD->getType().isConstQualified()) {
5307 FunctionDecl *CurFD = getCurFunctionDecl();
5308 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5309 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5310 diag::warn_static_local_in_extern_inline);
5311 MaybeSuggestAddingStaticToDecl(CurFD);
5312 }
5313 }
5314
Douglas Gregord023aec2011-09-09 20:53:38 +00005315 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00005316 if (IsVariableTemplateSpecialization)
5317 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5318 << (IsPartialSpecialization ? 1 : 0)
5319 << FixItHint::CreateRemoval(
5320 D.getDeclSpec().getModulePrivateSpecLoc());
5321 else if (IsExplicitSpecialization)
Douglas Gregord023aec2011-09-09 20:53:38 +00005322 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5323 << 2
5324 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregore3895852011-09-12 18:37:38 +00005325 else if (NewVD->hasLocalStorage())
5326 Diag(NewVD->getLocation(), diag::err_module_private_local)
5327 << 0 << NewVD->getDeclName()
5328 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5329 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo567f9172013-08-22 00:59:14 +00005330 else {
Douglas Gregord023aec2011-09-09 20:53:38 +00005331 NewVD->setModulePrivate();
Larisse Voufo567f9172013-08-22 00:59:14 +00005332 if (NewTemplate)
5333 NewTemplate->setModulePrivate();
5334 }
Douglas Gregord023aec2011-09-09 20:53:38 +00005335 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00005336
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005337 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005338 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005339
Richard Smithbe507b62013-02-01 08:12:08 +00005340 if (NewVD->hasAttrs())
5341 CheckAlignasUnderalignment(NewVD);
5342
Peter Collingbournec0c00662012-08-28 20:37:50 +00005343 if (getLangOpts().CUDA) {
5344 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5345 // storage [duration]."
5346 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola0db661e2012-12-21 01:21:33 +00005347 (NewVD->hasAttr<CUDASharedAttr>() ||
5348 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec0c00662012-08-28 20:37:50 +00005349 NewVD->setStorageClass(SC_Static);
Rafael Espindola0db661e2012-12-21 01:21:33 +00005350 }
Peter Collingbournec0c00662012-08-28 20:37:50 +00005351 }
5352
John McCallf85e1932011-06-15 23:02:42 +00005353 // In auto-retain/release, infer strong retension for variables of
5354 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00005355 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCallf85e1932011-06-15 23:02:42 +00005356 NewVD->setInvalidDecl();
5357
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005358 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner16c5dea2010-10-10 18:16:20 +00005359 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005360 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00005361 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner5f9e2722011-07-23 10:55:15 +00005362 StringRef Label = SE->getString();
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005363 if (S->getFnParent() != 0) {
5364 switch (SC) {
5365 case SC_None:
5366 case SC_Auto:
5367 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5368 break;
5369 case SC_Register:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00005370 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005371 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5372 break;
5373 case SC_Static:
5374 case SC_Extern:
5375 case SC_PrivateExtern:
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00005376 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00005377 break;
5378 }
5379 }
5380
5381 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindolabaf86952011-01-01 21:47:03 +00005382 Context, Label));
David Chisnall5f3c1632012-02-18 16:12:34 +00005383 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5384 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5385 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5386 if (I != ExtnameUndeclaredIdentifiers.end()) {
5387 NewVD->addAttr(I->second);
5388 ExtnameUndeclaredIdentifiers.erase(I);
5389 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005390 }
5391
John McCall8472af42010-03-16 21:48:18 +00005392 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00005393 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00005394 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00005395
John McCall68263142009-11-18 22:49:29 +00005396 // Don't consider existing declarations that are in a different
5397 // scope and are out-of-semantic-context declarations (if the new
5398 // declaration has linkage).
Larisse Voufoef4579c2013-08-06 01:03:05 +00005399 FilterLookupForScope(
Richard Smitha41c97a2013-09-20 01:15:31 +00005400 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
Larisse Voufoef4579c2013-08-06 01:03:05 +00005401 IsExplicitSpecialization || IsVariableTemplateSpecialization);
5402
Richard Smithdd9459f2013-08-13 18:18:50 +00005403 // Check whether the previous declaration is in the same block scope. This
5404 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5405 if (getLangOpts().CPlusPlus &&
5406 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5407 NewVD->setPreviousDeclInSameBlockScope(
5408 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smitha41c97a2013-09-20 01:15:31 +00005409 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smithdd9459f2013-08-13 18:18:50 +00005410
David Blaikie4e4d0842012-03-11 07:00:24 +00005411 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005412 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5413 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005414 // Merge the decl with the existing one if appropriate.
5415 if (!Previous.empty()) {
5416 if (Previous.isSingleResult() &&
5417 isa<FieldDecl>(Previous.getFoundDecl()) &&
5418 D.getCXXScopeSpec().isSet()) {
5419 // The user tried to define a non-static data member
5420 // out-of-line (C++ [dcl.meaning]p1).
5421 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5422 << D.getCXXScopeSpec().getRange();
5423 Previous.clear();
5424 NewVD->setInvalidDecl();
5425 }
5426 } else if (D.getCXXScopeSpec().isSet()) {
5427 // No previous declaration in the qualifying scope.
5428 Diag(D.getIdentifierLoc(), diag::err_no_member)
5429 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005430 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005431 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005432 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005433
Larisse Voufoef4579c2013-08-06 01:03:05 +00005434 if (!IsVariableTemplateSpecialization) {
5435 if (PrevVarTemplate) {
5436 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5437 LookupOrdinaryName, ForRedeclaration);
5438 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo567f9172013-08-22 00:59:14 +00005439 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005440 } else
Larisse Voufo567f9172013-08-22 00:59:14 +00005441 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufoef4579c2013-08-06 01:03:05 +00005442 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005443
5444 // This is an explicit specialization of a static data member. Check it.
Larisse Voufoef4579c2013-08-06 01:03:05 +00005445 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00005446 CheckMemberSpecialization(NewVD, Previous))
5447 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005448 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00005449
Rafael Espindola65611bf2013-03-02 21:41:48 +00005450 ProcessPragmaWeak(S, NewVD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00005451 checkAttributesAfterMerging(*this, *NewVD);
5452
Richard Smithaa4bc182013-06-30 09:48:50 +00005453 // If this is the first declaration of an extern C variable, update
5454 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00005455 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00005456 isIncompleteDeclExternC(*this, NewVD))
Richard Smith662f41b2013-06-18 20:15:12 +00005457 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005458
Reid Kleckner942f9fe2013-09-10 20:14:30 +00005459 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman5e867c82013-07-10 00:30:46 +00005460 Decl *ManglingContextDecl;
5461 if (MangleNumberingContext *MCtx =
5462 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5463 ManglingContextDecl)) {
5464 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5465 }
5466 }
5467
Larisse Voufoef4579c2013-08-06 01:03:05 +00005468 // If we are providing an explicit specialization of a static variable
5469 // template, make a note of that.
5470 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo04592e72013-08-22 00:28:27 +00005471 PrevVarTemplate->setMemberSpecialization();
Larisse Voufoef4579c2013-08-06 01:03:05 +00005472
Larisse Voufo567f9172013-08-22 00:59:14 +00005473 if (NewTemplate) {
5474 ActOnDocumentableDecl(NewTemplate);
5475 return NewTemplate;
Larisse Voufoef4579c2013-08-06 01:03:05 +00005476 }
5477
Larisse Voufo567f9172013-08-22 00:59:14 +00005478 return NewVD;
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005479}
5480
John McCall053f4bd2010-03-22 09:20:08 +00005481/// \brief Diagnose variable or built-in function shadowing. Implements
5482/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00005483///
John McCall053f4bd2010-03-22 09:20:08 +00005484/// This method is called whenever a VarDecl is added to a "useful"
5485/// scope.
John McCall8472af42010-03-16 21:48:18 +00005486///
John McCalla369a952010-03-20 04:12:52 +00005487/// \param S the scope in which the shadowing name is being declared
5488/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00005489///
John McCall053f4bd2010-03-22 09:20:08 +00005490void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00005491 // Return if warning is ignored.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005492 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005493 DiagnosticsEngine::Ignored)
John McCall8472af42010-03-16 21:48:18 +00005494 return;
5495
Argyrios Kyrtzidis651f86f2011-02-08 18:21:25 +00005496 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005497 if (D->hasGlobalStorage())
John McCall8472af42010-03-16 21:48:18 +00005498 return;
Argyrios Kyrtzidis865dd8c2011-04-25 21:39:50 +00005499
5500 DeclContext *NewDC = D->getDeclContext();
5501
John McCalla369a952010-03-20 04:12:52 +00005502 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00005503 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00005504 return;
John McCall8472af42010-03-16 21:48:18 +00005505
John McCall8472af42010-03-16 21:48:18 +00005506 NamedDecl* ShadowedDecl = R.getFoundDecl();
5507 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5508 return;
5509
Argyrios Kyrtzidis36eb5e42011-01-31 07:04:54 +00005510 // Fields are not shadowed by variables in C++ static methods.
5511 if (isa<FieldDecl>(ShadowedDecl))
5512 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5513 if (MD->isStatic())
5514 return;
5515
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005516 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5517 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00005518 // For shadowing external vars, make sure that we point to the global
5519 // declaration, not a locally scoped extern declaration.
5520 for (VarDecl::redecl_iterator
5521 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5522 I != E; ++I)
5523 if (I->isFileVarDecl()) {
5524 ShadowedDecl = *I;
5525 break;
5526 }
5527 }
5528
5529 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5530
John McCalla369a952010-03-20 04:12:52 +00005531 // Only warn about certain kinds of shadowing for class members.
5532 if (NewDC && NewDC->isRecord()) {
5533 // In particular, don't warn about shadowing non-class members.
5534 if (!OldDC->isRecord())
5535 return;
5536
5537 // TODO: should we warn about static data members shadowing
5538 // static data members from base classes?
5539
5540 // TODO: don't diagnose for inaccessible shadowed members.
5541 // This is hard to do perfectly because we might friend the
5542 // shadowing context, but that's just a false negative.
5543 }
5544
5545 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00005546 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00005547 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00005548 if (isa<FieldDecl>(ShadowedDecl))
5549 Kind = 3; // field
5550 else
5551 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00005552 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00005553 Kind = 1; // global
5554 else
5555 Kind = 0; // local
5556
John McCalla369a952010-03-20 04:12:52 +00005557 DeclarationName Name = R.getLookupName();
5558
John McCall8472af42010-03-16 21:48:18 +00005559 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00005560 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00005561 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5562}
5563
John McCall053f4bd2010-03-22 09:20:08 +00005564/// \brief Check -Wshadow without the advantage of a previous lookup.
5565void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005566 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikied6471f72011-09-25 23:23:43 +00005567 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005568 return;
5569
John McCall053f4bd2010-03-22 09:20:08 +00005570 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5571 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5572 LookupName(R, S);
5573 CheckShadow(S, D, R);
5574}
5575
Richard Smithaa4bc182013-06-30 09:48:50 +00005576/// Check for conflict between this global or extern "C" declaration and
5577/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola294ddc62013-01-11 19:34:23 +00005578template<typename T>
Richard Smithaa4bc182013-06-30 09:48:50 +00005579static bool checkGlobalOrExternCConflict(
5580 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5581 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5582 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005583
Richard Smithaa4bc182013-06-30 09:48:50 +00005584 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5585 // The common case: this global doesn't conflict with any extern "C"
5586 // declaration.
5587 return false;
5588 }
5589
5590 if (Prev) {
5591 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5592 // Both the old and new declarations have C language linkage. This is a
5593 // redeclaration.
5594 Previous.clear();
5595 Previous.addDecl(Prev);
5596 return true;
5597 }
5598
5599 // This is a global, non-extern "C" declaration, and there is a previous
5600 // non-global extern "C" declaration. Diagnose if this is a variable
5601 // declaration.
5602 if (!isa<VarDecl>(ND))
5603 return false;
5604 } else {
5605 // The declaration is extern "C". Check for any declaration in the
5606 // translation unit which might conflict.
5607 if (IsGlobal) {
5608 // We have already performed the lookup into the translation unit.
5609 IsGlobal = false;
5610 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5611 I != E; ++I) {
5612 if (isa<VarDecl>(*I)) {
5613 Prev = *I;
5614 break;
5615 }
5616 }
5617 } else {
5618 DeclContext::lookup_result R =
5619 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5620 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5621 I != E; ++I) {
5622 if (isa<VarDecl>(*I)) {
5623 Prev = *I;
5624 break;
5625 }
5626 // FIXME: If we have any other entity with this name in global scope,
5627 // the declaration is ill-formed, but that is a defect: it breaks the
5628 // 'stat' hack, for instance. Only variables can have mangled name
5629 // clashes with extern "C" declarations, so only they deserve a
5630 // diagnostic.
5631 }
5632 }
5633
5634 if (!Prev)
Rafael Espindola2d1b0962013-03-14 03:07:35 +00005635 return false;
5636 }
5637
Richard Smithaa4bc182013-06-30 09:48:50 +00005638 // Use the first declaration's location to ensure we point at something which
5639 // is lexically inside an extern "C" linkage-spec.
5640 assert(Prev && "should have found a previous declaration to diagnose");
5641 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindolabc650912013-10-17 15:37:26 +00005642 Prev = FD->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005643 else
Rafael Espindolabc650912013-10-17 15:37:26 +00005644 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithaa4bc182013-06-30 09:48:50 +00005645
5646 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5647 << IsGlobal << ND;
5648 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5649 << IsGlobal;
5650 return false;
5651}
5652
5653/// Apply special rules for handling extern "C" declarations. Returns \c true
5654/// if we have found that this is a redeclaration of some prior entity.
5655///
5656/// Per C++ [dcl.link]p6:
5657/// Two declarations [for a function or variable] with C language linkage
5658/// with the same name that appear in different scopes refer to the same
5659/// [entity]. An entity with C language linkage shall not be declared with
5660/// the same name as an entity in global scope.
5661template<typename T>
5662static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5663 LookupResult &Previous) {
5664 if (!S.getLangOpts().CPlusPlus) {
5665 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smitha41c97a2013-09-20 01:15:31 +00005666 // variable declared in function scope. We don't need this in C++, because
5667 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithaa4bc182013-06-30 09:48:50 +00005668 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5669 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5670 Previous.clear();
5671 Previous.addDecl(Prev);
5672 return true;
5673 }
5674 }
5675 return false;
5676 }
5677
5678 // A declaration in the translation unit can conflict with an extern "C"
5679 // declaration.
5680 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5681 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5682
5683 // An extern "C" declaration can conflict with a declaration in the
5684 // translation unit or can be a redeclaration of an extern "C" declaration
5685 // in another scope.
5686 if (isIncompleteDeclExternC(S,ND))
5687 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5688
5689 // Neither global nor extern "C": nothing to do.
5690 return false;
Rafael Espindola294ddc62013-01-11 19:34:23 +00005691}
5692
Richard Smithdc7a4f52013-04-30 13:56:41 +00005693void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00005694 // If the decl is already known invalid, don't check it.
5695 if (NewVD->isInvalidDecl())
Richard Smithdc7a4f52013-04-30 13:56:41 +00005696 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005697
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005698 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5699 QualType T = TInfo->getType();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005700
Richard Smithdc7a4f52013-04-30 13:56:41 +00005701 // Defer checking an 'auto' type until its initializer is attached.
5702 if (T->isUndeducedType())
5703 return;
5704
John McCallc12c5bb2010-05-15 11:32:37 +00005705 if (T->isObjCObjectType()) {
Fariborz Jahaniandcf10112011-07-25 21:12:27 +00005706 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5707 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00005708 T = Context.getObjCObjectPointerType(T);
5709 NewVD->setType(T);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005710 }
Mike Stump1eb44332009-09-09 15:08:12 +00005711
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005712 // Emit an error if an address space was applied to decl with local storage.
5713 // This includes arrays of objects with address space qualifiers, but not
5714 // automatic variables that point to other address spaces.
5715 // ISO/IEC TR 18037 S5.1.2
Chris Lattner16c5dea2010-10-10 18:16:20 +00005716 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005717 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005718 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005719 return;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005720 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00005721
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005722 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5723 // __constant address space.
5724 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5725 && T.getAddressSpace() != LangAS::opencl_constant
5726 && !T->isSamplerT()){
5727 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5728 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005729 return;
Tanya Lattner8aa86d12013-04-05 20:14:50 +00005730 }
5731
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005732 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5733 // scope.
5734 if ((getLangOpts().OpenCLVersion >= 120)
5735 && NewVD->isStaticLocal()) {
5736 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5737 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005738 return;
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00005739 }
5740
Mike Stumpf33651c2009-04-14 00:57:29 +00005741 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanian175df892011-06-07 20:15:46 +00005742 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005743 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanian175df892011-06-07 20:15:46 +00005744 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005745 else {
5746 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanian175df892011-06-07 20:15:46 +00005747 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek3ba17ee2012-10-02 05:36:02 +00005748 }
Fariborz Jahanian175df892011-06-07 20:15:46 +00005749 }
Chris Lattner16c5dea2010-10-10 18:16:20 +00005750
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005751 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00005752 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00005753 NewVD->hasAttr<BlocksAttr>())
John McCall781472f2010-08-25 08:40:02 +00005754 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00005755
Chris Lattner38c5ebd2009-04-19 05:21:20 +00005756 if ((isVM && NewVD->hasLinkage()) ||
5757 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005758 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00005759 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005760 TypeSourceInfo *FixedTInfo =
5761 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5762 SizeIsNegative, Oversized);
5763 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00005764 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00005765 // FIXME: This won't give the correct result for
5766 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005767 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005768
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005769 if (NewVD->isFileVarDecl())
5770 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005771 << SizeRange;
Enea Zaffanella9cbcab82013-05-10 20:34:44 +00005772 else if (NewVD->isStaticLocal())
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005773 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005774 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005775 else
5776 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00005777 << SizeRange;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005778 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005779 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005780 }
5781
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005782 if (FixedTInfo == 0) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005783 if (NewVD->isFileVarDecl())
5784 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5785 else
5786 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005787 NewVD->setInvalidDecl();
Richard Smithdc7a4f52013-04-30 13:56:41 +00005788 return;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005789 }
Mike Stump1eb44332009-09-09 15:08:12 +00005790
Chris Lattnereaaebc72009-04-25 08:06:05 +00005791 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnaraeae859a2012-11-08 16:01:51 +00005792 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara4c5750e2012-11-08 14:44:42 +00005793 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00005794 }
5795
David Majnemeraa715672013-05-29 00:56:45 +00005796 if (T->isVoidType()) {
5797 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5798 // of objects and functions.
5799 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5800 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5801 << T;
5802 NewVD->setInvalidDecl();
5803 return;
5804 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00005805 }
5806
5807 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5808 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5809 NewVD->setInvalidDecl();
5810 return;
5811 }
5812
5813 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5814 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5815 NewVD->setInvalidDecl();
5816 return;
5817 }
5818
5819 if (NewVD->isConstexpr() && !T->isDependentType() &&
5820 RequireLiteralType(NewVD->getLocation(), T,
5821 diag::err_constexpr_var_non_literal)) {
5822 // Can't perform this check until the type is deduced.
5823 NewVD->setInvalidDecl();
5824 return;
5825 }
5826}
5827
5828/// \brief Perform semantic checking on a newly-created variable
5829/// declaration.
5830///
5831/// This routine performs all of the type-checking required for a
5832/// variable declaration once it has been built. It is used both to
5833/// check variables after they have been parsed and their declarators
5834/// have been translated into a declaration, and to check variables
5835/// that have been instantiated from a template.
5836///
5837/// Sets NewVD->isInvalidDecl() if an error was encountered.
5838///
5839/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo567f9172013-08-22 00:59:14 +00005840bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00005841 CheckVariableDeclarationType(NewVD);
5842
5843 // If the decl is already known invalid, don't check it.
5844 if (NewVD->isInvalidDecl())
5845 return false;
5846
John McCall5b8740f2013-04-01 18:34:28 +00005847 // If we did not find anything by this name, look for a non-visible
5848 // extern "C" declaration with the same name.
Richard Smithdd9459f2013-08-13 18:18:50 +00005849 if (Previous.empty() &&
5850 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith99a72382013-09-03 21:00:58 +00005851 Previous.setShadowed();
Douglas Gregor63935192009-03-02 00:19:53 +00005852
Douglas Gregor7dc80e12013-01-09 00:47:56 +00005853 // Filter out any non-conflicting previous declarations.
5854 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5855
John McCall68263142009-11-18 22:49:29 +00005856 if (!Previous.empty()) {
Richard Smith99a72382013-09-03 21:00:58 +00005857 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005858 return true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005859 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00005860 return false;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00005861}
5862
Douglas Gregora8f32e02009-10-06 17:59:45 +00005863/// \brief Data used with FindOverriddenMethod
5864struct FindOverriddenMethodData {
5865 Sema *S;
5866 CXXMethodDecl *Method;
5867};
5868
5869/// \brief Member lookup function that determines whether a given C++
5870/// method overrides a method in a base class, to be used with
5871/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00005872static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00005873 CXXBasePath &Path,
5874 void *UserData) {
5875 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00005876
Douglas Gregora8f32e02009-10-06 17:59:45 +00005877 FindOverriddenMethodData *Data
5878 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00005879
5880 DeclarationName Name = Data->Method->getDeclName();
5881
5882 // FIXME: Do we care about other names here too?
5883 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00005884 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00005885 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5886 CanQualType CT = Data->S->Context.getCanonicalType(T);
5887
Anders Carlsson1a689722009-11-27 01:26:58 +00005888 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00005889 }
5890
5891 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005892 !Path.Decls.empty();
5893 Path.Decls = Path.Decls.slice(1)) {
5894 NamedDecl *D = Path.Decls.front();
John McCallad00b772010-06-16 08:42:20 +00005895 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5896 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00005897 return true;
5898 }
5899 }
5900
5901 return false;
5902}
5903
David Blaikie5708c182012-10-17 00:47:58 +00005904namespace {
5905 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5906}
5907/// \brief Report an error regarding overriding, along with any relevant
5908/// overriden methods.
5909///
5910/// \param DiagID the primary error to report.
5911/// \param MD the overriding method.
5912/// \param OEK which overrides to include as notes.
5913static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5914 OverrideErrorKind OEK = OEK_All) {
5915 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5916 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5917 E = MD->end_overridden_methods();
5918 I != E; ++I) {
5919 // This check (& the OEK parameter) could be replaced by a predicate, but
5920 // without lambdas that would be overkill. This is still nicer than writing
5921 // out the diag loop 3 times.
5922 if ((OEK == OEK_All) ||
5923 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5924 (OEK == OEK_Deleted && (*I)->isDeleted()))
5925 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5926 }
5927}
5928
Sebastian Redla165da02009-11-18 21:51:29 +00005929/// AddOverriddenMethods - See if a method overrides any in the base classes,
5930/// and if so, check that it's a valid override and remember it.
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005931bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redla165da02009-11-18 21:51:29 +00005932 // Look for virtual methods in base classes that this method might override.
5933 CXXBasePaths Paths;
5934 FindOverriddenMethodData Data;
5935 Data.Method = MD;
5936 Data.S = this;
David Blaikie5708c182012-10-17 00:47:58 +00005937 bool hasDeletedOverridenMethods = false;
5938 bool hasNonDeletedOverridenMethods = false;
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005939 bool AddedAny = false;
Sebastian Redla165da02009-11-18 21:51:29 +00005940 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5941 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5942 E = Paths.found_decls_end(); I != E; ++I) {
5943 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu304e2332011-07-01 20:02:53 +00005944 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00005945 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballmanfff32482012-12-09 17:45:41 +00005946 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithb9d0b762012-07-27 04:22:15 +00005947 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson2e1c7302011-01-20 16:25:36 +00005948 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie5708c182012-10-17 00:47:58 +00005949 hasDeletedOverridenMethods |= OldMD->isDeleted();
5950 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005951 AddedAny = true;
5952 }
Sebastian Redla165da02009-11-18 21:51:29 +00005953 }
5954 }
5955 }
David Blaikie5708c182012-10-17 00:47:58 +00005956
5957 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5958 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5959 }
5960 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5961 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5962 }
5963
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00005964 return AddedAny;
Sebastian Redla165da02009-11-18 21:51:29 +00005965}
5966
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005967namespace {
5968 // Struct for holding all of the extra arguments needed by
5969 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5970 struct ActOnFDArgs {
5971 Scope *S;
5972 Declarator &D;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005973 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00005974 bool AddToScope;
5975 };
5976}
5977
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005978namespace {
5979
5980// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005981// Also only accept corrections that have the same parent decl.
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005982class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5983 public:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005984 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5985 CXXRecordDecl *Parent)
5986 : Context(Context), OriginalFD(TypoFD),
5987 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005988
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00005989 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain33363532012-02-16 22:40:59 +00005990 if (candidate.getEditDistance() == 0)
5991 return false;
5992
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005993 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00005994 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5995 CDeclEnd = candidate.end();
5996 CDecl != CDeclEnd; ++CDecl) {
5997 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5998
5999 if (FD && !FD->hasBody() &&
6000 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6001 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6002 CXXRecordDecl *Parent = MD->getParent();
6003 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6004 return true;
6005 } else if (!ExpectedParent) {
6006 return true;
6007 }
6008 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006009 }
6010
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006011 return false;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006012 }
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006013
6014 private:
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006015 ASTContext &Context;
6016 FunctionDecl *OriginalFD;
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006017 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00006018};
6019
6020}
6021
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006022/// \brief Generate diagnostics for an invalid function redeclaration.
6023///
6024/// This routine handles generating the diagnostic messages for an invalid
6025/// function redeclaration, including finding possible similar declarations
6026/// or performing typo correction if there are no previous declarations with
6027/// the same name.
6028///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006029/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006030/// the new declaration name does not cause new errors.
Richard Smith4e9686b2013-08-09 04:35:01 +00006031static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006032 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith4e9686b2013-08-09 04:35:01 +00006033 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006034 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006035 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006036 SmallVector<unsigned, 1> MismatchedParams;
6037 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006038 TypoCorrection Correction;
Richard Smith2d670972013-08-17 00:46:16 +00006039 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith4e9686b2013-08-09 04:35:01 +00006040 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6041 : diag::err_member_decl_does_not_match;
6042 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6043 IsLocalFriend ? Sema::LookupLocalFriendName
6044 : Sema::LookupOrdinaryName,
6045 Sema::ForRedeclaration);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006046
6047 NewFD->setInvalidDecl();
Richard Smith4e9686b2013-08-09 04:35:01 +00006048 if (IsLocalFriend)
6049 SemaRef.LookupName(Prev, S);
6050 else
6051 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCall29ae6e52010-10-13 05:45:15 +00006052 assert(!Prev.isAmbiguous() &&
6053 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain33363532012-02-16 22:40:59 +00006054 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006055 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6056 MD ? MD->getParent() : 0);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006057 if (!Prev.empty()) {
6058 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6059 Func != FuncEnd; ++Func) {
6060 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006061 if (FD &&
6062 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006063 // Add 1 to the index so that 0 can mean the mismatch didn't
6064 // involve a parameter
6065 unsigned ParamNum =
6066 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6067 NearMatches.push_back(std::make_pair(FD, ParamNum));
6068 }
Kaelyn Uhrain4d9d1572011-08-04 17:40:00 +00006069 }
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006070 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith4e9686b2013-08-09 04:35:01 +00006071 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smith2d670972013-08-17 00:46:16 +00006072 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6073 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6074 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006075 // Set up everything for the call to ActOnFunctionDeclarator
6076 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6077 ExtraArgs.D.getIdentifierLoc());
6078 Previous.clear();
6079 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006080 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6081 CDeclEnd = Correction.end();
6082 CDecl != CDeclEnd; ++CDecl) {
6083 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrainef094a12012-06-07 23:57:08 +00006084 if (FD && !FD->hasBody() &&
6085 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006086 Previous.addDecl(FD);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006087 }
6088 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006089 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smith2d670972013-08-17 00:46:16 +00006090
6091 NamedDecl *Result;
6092 // Retry building the function declaration with the new previous
6093 // declarations, and with errors suppressed.
6094 {
6095 // Trap errors.
6096 Sema::SFINAETrap Trap(SemaRef);
6097
6098 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6099 // pieces need to verify the typo-corrected C++ declaration and hopefully
6100 // eliminate the need for the parameter pack ExtraArgs.
6101 Result = SemaRef.ActOnFunctionDeclarator(
6102 ExtraArgs.S, ExtraArgs.D,
6103 Correction.getCorrectionDecl()->getDeclContext(),
6104 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6105 ExtraArgs.AddToScope);
6106
6107 if (Trap.hasErrorOccurred())
6108 Result = 0;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006109 }
Richard Smith2d670972013-08-17 00:46:16 +00006110
6111 if (Result) {
6112 // Determine which correction we picked.
6113 Decl *Canonical = Result->getCanonicalDecl();
6114 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6115 I != E; ++I)
6116 if ((*I)->getCanonicalDecl() == Canonical)
6117 Correction.setCorrectionDecl(*I);
6118
6119 SemaRef.diagnoseTypo(
6120 Correction,
6121 SemaRef.PDiag(IsLocalFriend
6122 ? diag::err_no_matching_local_friend_suggest
6123 : diag::err_member_decl_does_not_match_suggest)
6124 << Name << NewDC << IsDefinition);
6125 return Result;
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00006126 }
Richard Smith2d670972013-08-17 00:46:16 +00006127
6128 // Pretend the typo correction never occurred
6129 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6130 ExtraArgs.D.getIdentifierLoc());
6131 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6132 Previous.clear();
6133 Previous.setLookupName(Name);
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006134 }
6135
Richard Smith2d670972013-08-17 00:46:16 +00006136 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6137 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006138
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006139 bool NewFDisConst = false;
6140 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikie4ef832f2012-08-10 00:55:35 +00006141 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006142
Craig Topper8bc99dd2013-07-04 03:15:42 +00006143 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006144 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6145 NearMatch != NearMatchEnd; ++NearMatch) {
6146 FunctionDecl *FD = NearMatch->first;
Richard Smith4e9686b2013-08-09 04:35:01 +00006147 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6148 bool FDisConst = MD && MD->isConst();
6149 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006150
Richard Smitha41c97a2013-09-20 01:15:31 +00006151 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006152 if (unsigned Idx = NearMatch->second) {
6153 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smith1c931be2012-04-02 18:40:40 +00006154 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6155 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith4e9686b2013-08-09 04:35:01 +00006156 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6157 : diag::note_local_decl_close_param_match)
6158 << Idx << FDParam->getType()
6159 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006160 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00006161 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain10553932011-10-10 18:01:37 +00006162 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrain51611632011-08-18 18:19:12 +00006163 } else
Richard Smith4e9686b2013-08-09 04:35:01 +00006164 SemaRef.Diag(FD->getLocation(),
6165 IsMember ? diag::note_member_def_close_match
6166 : diag::note_local_decl_close_match);
John McCall29ae6e52010-10-13 05:45:15 +00006167 }
Richard Smith2d670972013-08-17 00:46:16 +00006168 return 0;
John McCall29ae6e52010-10-13 05:45:15 +00006169}
6170
David Blaikied662a792011-10-19 22:56:21 +00006171static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6172 Declarator &D) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006173 switch (D.getDeclSpec().getStorageClassSpec()) {
6174 default: llvm_unreachable("Unknown storage class!");
6175 case DeclSpec::SCS_auto:
6176 case DeclSpec::SCS_register:
6177 case DeclSpec::SCS_mutable:
6178 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6179 diag::err_typecheck_sclass_func);
6180 D.setInvalidType();
6181 break;
6182 case DeclSpec::SCS_unspecified: break;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00006183 case DeclSpec::SCS_extern:
6184 if (D.getDeclSpec().isExternInLinkageSpec())
6185 return SC_None;
6186 return SC_Extern;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006187 case DeclSpec::SCS_static: {
6188 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6189 // C99 6.7.1p5:
6190 // The declaration of an identifier for a function that has
6191 // block scope shall have no explicit storage-class specifier
6192 // other than extern
6193 // See also (C++ [dcl.stc]p4).
6194 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6195 diag::err_static_block_func);
6196 break;
6197 } else
6198 return SC_Static;
6199 }
6200 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6201 }
6202
6203 // No explicit storage class has already been returned
6204 return SC_None;
6205}
6206
6207static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6208 DeclContext *DC, QualType &R,
6209 TypeSourceInfo *TInfo,
6210 FunctionDecl::StorageClass SC,
6211 bool &IsVirtualOkay) {
6212 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6213 DeclarationName Name = NameInfo.getName();
6214
6215 FunctionDecl *NewFD = 0;
6216 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006217
David Blaikie4e4d0842012-03-11 07:00:24 +00006218 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006219 // Determine whether the function was written with a
6220 // prototype. This true when:
6221 // - there is a prototype in the declarator, or
6222 // - the type R of the function is some kind of typedef or other reference
6223 // to a type name (which eventually refers to a function type).
6224 bool HasPrototype =
6225 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6226 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6227
David Blaikied662a792011-10-19 22:56:21 +00006228 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006229 D.getLocStart(), NameInfo, R,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006230 TInfo, SC, isInline,
6231 HasPrototype, false);
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006232 if (D.isInvalidType())
6233 NewFD->setInvalidDecl();
6234
6235 // Set the lexical context.
6236 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6237
6238 return NewFD;
6239 }
6240
6241 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6242 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6243
6244 // Check that the return type is not an abstract class type.
6245 // For record types, this is done by the AbstractClassUsageDiagnoser once
6246 // the class has been completely parsed.
6247 if (!DC->isRecord() &&
6248 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6249 R->getAs<FunctionType>()->getResultType(),
6250 diag::err_abstract_type_in_decl,
6251 SemaRef.AbstractReturnType))
6252 D.setInvalidType();
6253
6254 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6255 // This is a C++ constructor declaration.
6256 assert(DC->isRecord() &&
6257 "Constructors can only be declared in a member context");
6258
6259 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6260 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006261 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006262 R, TInfo, isExplicit, isInline,
6263 /*isImplicitlyDeclared=*/false,
6264 isConstexpr);
6265
6266 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6267 // This is a C++ destructor declaration.
6268 if (DC->isRecord()) {
6269 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6270 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6271 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6272 SemaRef.Context, Record,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006273 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006274 NameInfo, R, TInfo, isInline,
6275 /*isImplicitlyDeclared=*/false);
6276
6277 // If the class is complete, then we now create the implicit exception
6278 // specification. If the class is incomplete or dependent, we can't do
6279 // it yet.
Richard Smith80ad52f2013-01-02 11:42:31 +00006280 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006281 Record->getDefinition() && !Record->isBeingDefined() &&
6282 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6283 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6284 }
6285
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006286 // The Microsoft ABI requires that we perform the destructor body
6287 // checks (i.e. operator delete() lookup) at every declaration, as
6288 // any translation unit may need to emit a deleting destructor.
6289 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6290 !Record->isDependentType() && Record->getDefinition() &&
6291 !Record->isBeingDefined()) {
6292 SemaRef.CheckDestructor(NewDD);
6293 }
6294
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006295 IsVirtualOkay = true;
6296 return NewDD;
6297
6298 } else {
6299 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6300 D.setInvalidType();
6301
6302 // Create a FunctionDecl to satisfy the function definition parsing
6303 // code path.
6304 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006305 D.getLocStart(),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006306 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006307 SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006308 /*hasPrototype=*/true, isConstexpr);
6309 }
6310
6311 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6312 if (!DC->isRecord()) {
6313 SemaRef.Diag(D.getIdentifierLoc(),
6314 diag::err_conv_function_not_member);
6315 return 0;
6316 }
6317
6318 SemaRef.CheckConversionDeclarator(D, R, SC);
6319 IsVirtualOkay = true;
6320 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar96a00142012-03-09 18:35:03 +00006321 D.getLocStart(), NameInfo,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006322 R, TInfo, isInline, isExplicit,
6323 isConstexpr, SourceLocation());
6324
6325 } else if (DC->isRecord()) {
6326 // If the name of the function is the same as the name of the record,
6327 // then this must be an invalid constructor that has a return type.
6328 // (The parser checks for a return type and makes the declarator a
6329 // constructor if it has no return type).
6330 if (Name.getAsIdentifierInfo() &&
6331 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6332 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6333 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6334 << SourceRange(D.getIdentifierLoc());
6335 return 0;
6336 }
6337
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006338 // This is a C++ method declaration.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006339 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6340 cast<CXXRecordDecl>(DC),
6341 D.getLocStart(), NameInfo, R,
6342 TInfo, SC, isInline,
6343 isConstexpr, SourceLocation());
6344 IsVirtualOkay = !Ret->isStatic();
6345 return Ret;
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006346 } else {
6347 // Determine whether the function was written with a
6348 // prototype. This true when:
6349 // - we're in C++ (where every function has a prototype),
6350 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar96a00142012-03-09 18:35:03 +00006351 D.getLocStart(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00006352 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006353 true/*HasPrototype*/, isConstexpr);
6354 }
6355}
6356
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006357void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6358 // In C++, the empty parameter-type-list must be spelled "void"; a
6359 // typedef of void is not permitted.
6360 if (getLangOpts().CPlusPlus &&
6361 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6362 bool IsTypeAlias = false;
6363 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6364 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6365 else if (const TemplateSpecializationType *TST =
6366 Param->getType()->getAs<TemplateSpecializationType>())
6367 IsTypeAlias = TST->isTypeAlias();
6368 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6369 << IsTypeAlias;
6370 }
6371}
6372
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00006373enum OpenCLParamType {
6374 ValidKernelParam,
6375 PtrPtrKernelParam,
6376 PtrKernelParam,
6377 InvalidKernelParam,
6378 RecordKernelParam
6379};
6380
6381static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6382 if (PT->isPointerType()) {
6383 QualType PointeeType = PT->getPointeeType();
6384 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6385 }
6386
6387 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6388 // be used as builtin types.
6389
6390 if (PT->isImageType())
6391 return PtrKernelParam;
6392
6393 if (PT->isBooleanType())
6394 return InvalidKernelParam;
6395
6396 if (PT->isEventT())
6397 return InvalidKernelParam;
6398
6399 if (PT->isHalfType())
6400 return InvalidKernelParam;
6401
6402 if (PT->isRecordType())
6403 return RecordKernelParam;
6404
6405 return ValidKernelParam;
6406}
6407
6408static void checkIsValidOpenCLKernelParameter(
6409 Sema &S,
6410 Declarator &D,
6411 ParmVarDecl *Param,
6412 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6413 QualType PT = Param->getType();
6414
6415 // Cache the valid types we encounter to avoid rechecking structs that are
6416 // used again
6417 if (ValidTypes.count(PT.getTypePtr()))
6418 return;
6419
6420 switch (getOpenCLKernelParameterType(PT)) {
6421 case PtrPtrKernelParam:
6422 // OpenCL v1.2 s6.9.a:
6423 // A kernel function argument cannot be declared as a
6424 // pointer to a pointer type.
6425 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6426 D.setInvalidType();
6427 return;
6428
6429 // OpenCL v1.2 s6.9.k:
6430 // Arguments to kernel functions in a program cannot be declared with the
6431 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6432 // uintptr_t or a struct and/or union that contain fields declared to be
6433 // one of these built-in scalar types.
6434
6435 case InvalidKernelParam:
6436 // OpenCL v1.2 s6.8 n:
6437 // A kernel function argument cannot be declared
6438 // of event_t type.
6439 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6440 D.setInvalidType();
6441 return;
6442
6443 case PtrKernelParam:
6444 case ValidKernelParam:
6445 ValidTypes.insert(PT.getTypePtr());
6446 return;
6447
6448 case RecordKernelParam:
6449 break;
6450 }
6451
6452 // Track nested structs we will inspect
6453 SmallVector<const Decl *, 4> VisitStack;
6454
6455 // Track where we are in the nested structs. Items will migrate from
6456 // VisitStack to HistoryStack as we do the DFS for bad field.
6457 SmallVector<const FieldDecl *, 4> HistoryStack;
6458 HistoryStack.push_back((const FieldDecl *) 0);
6459
6460 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6461 VisitStack.push_back(PD);
6462
6463 assert(VisitStack.back() && "First decl null?");
6464
6465 do {
6466 const Decl *Next = VisitStack.pop_back_val();
6467 if (!Next) {
6468 assert(!HistoryStack.empty());
6469 // Found a marker, we have gone up a level
6470 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6471 ValidTypes.insert(Hist->getType().getTypePtr());
6472
6473 continue;
6474 }
6475
6476 // Adds everything except the original parameter declaration (which is not a
6477 // field itself) to the history stack.
6478 const RecordDecl *RD;
6479 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6480 HistoryStack.push_back(Field);
6481 RD = Field->getType()->castAs<RecordType>()->getDecl();
6482 } else {
6483 RD = cast<RecordDecl>(Next);
6484 }
6485
6486 // Add a null marker so we know when we've gone back up a level
6487 VisitStack.push_back((const Decl *) 0);
6488
6489 for (RecordDecl::field_iterator I = RD->field_begin(),
6490 E = RD->field_end(); I != E; ++I) {
6491 const FieldDecl *FD = *I;
6492 QualType QT = FD->getType();
6493
6494 if (ValidTypes.count(QT.getTypePtr()))
6495 continue;
6496
6497 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6498 if (ParamType == ValidKernelParam)
6499 continue;
6500
6501 if (ParamType == RecordKernelParam) {
6502 VisitStack.push_back(FD);
6503 continue;
6504 }
6505
6506 // OpenCL v1.2 s6.9.p:
6507 // Arguments to kernel functions that are declared to be a struct or union
6508 // do not allow OpenCL objects to be passed as elements of the struct or
6509 // union.
6510 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6511 S.Diag(Param->getLocation(),
6512 diag::err_record_with_pointers_kernel_param)
6513 << PT->isUnionType()
6514 << PT;
6515 } else {
6516 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6517 }
6518
6519 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6520 << PD->getDeclName();
6521
6522 // We have an error, now let's go back up through history and show where
6523 // the offending field came from
6524 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6525 E = HistoryStack.end(); I != E; ++I) {
6526 const FieldDecl *OuterField = *I;
6527 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6528 << OuterField->getType();
6529 }
6530
6531 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6532 << QT->isPointerType()
6533 << QT;
6534 D.setInvalidType();
6535 return;
6536 }
6537 } while (!VisitStack.empty());
6538}
6539
Mike Stump1eb44332009-09-09 15:08:12 +00006540NamedDecl*
Nick Lewycky25af0912011-07-02 02:05:12 +00006541Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006542 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00006543 MultiTemplateParamsArg TemplateParamLists,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006544 bool &AddToScope) {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006545 QualType R = TInfo->getType();
6546
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006547 assert(R.getTypePtr()->isFunctionType());
6548
Abramo Bagnara25777432010-08-11 22:01:17 +00006549 // TODO: consider using NameInfo for diagnostic.
6550 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6551 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006552 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006553
Richard Smithec642442013-04-12 22:46:28 +00006554 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6555 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6556 diag::err_invalid_thread)
6557 << DeclSpec::getSpecifierName(TSCS);
Eli Friedman63054b32009-04-19 20:27:55 +00006558
Reid Klecknerd1a32c32013-10-08 00:58:57 +00006559 if (D.isFirstDeclarationOfMember())
6560 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckneref072032013-08-27 23:08:25 +00006561
Douglas Gregor3922ed02010-12-10 19:28:19 +00006562 bool isFriend = false;
Douglas Gregor3922ed02010-12-10 19:28:19 +00006563 FunctionTemplateDecl *FunctionTemplate = 0;
6564 bool isExplicitSpecialization = false;
6565 bool isFunctionTemplateSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006566
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006567 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber6b020092012-06-25 17:21:05 +00006568 bool HasExplicitTemplateArgs = false;
6569 TemplateArgumentListInfo TemplateArgs;
6570
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006571 bool isVirtualOkay = false;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006572
Richard Smitha41c97a2013-09-20 01:15:31 +00006573 DeclContext *OriginalDC = DC;
6574 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6575
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006576 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6577 isVirtualOkay);
6578 if (!NewFD) return 0;
6579
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00006580 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6581 NewFD->setTopLevelDeclInObjCContainer();
6582
Richard Smitha41c97a2013-09-20 01:15:31 +00006583 // Set the lexical context. If this is a function-scope declaration, or has a
6584 // C++ scope specifier, or is the object of a friend declaration, the lexical
6585 // context will be different from the semantic context.
6586 NewFD->setLexicalDeclContext(CurContext);
6587
6588 if (IsLocalExternDecl)
6589 NewFD->setLocalExternDecl();
6590
David Blaikie4e4d0842012-03-11 07:00:24 +00006591 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006592 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00006593 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6594 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006595 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006596 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006597 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnarab0a2fcc2011-03-18 15:21:59 +00006598 // C++ [class.friend]p5
6599 // A function can be defined in a friend declaration of a
6600 // class . . . . Such a function is implicitly inline.
6601 NewFD->setImplicitlyInline();
6602 }
6603
John McCalle402e722012-09-25 07:32:39 +00006604 // If this is a method defined in an __interface, and is not a constructor
6605 // or an overloaded operator, then set the pure flag (isVirtual will already
6606 // return true).
6607 if (const CXXRecordDecl *Parent =
6608 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6609 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matos6666ed42012-08-31 18:45:21 +00006610 NewFD->setPure(true);
6611 }
6612
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006613 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006614 isExplicitSpecialization = false;
6615 isFunctionTemplateSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006616 if (D.isInvalidType())
6617 NewFD->setInvalidDecl();
Richard Smitha41c97a2013-09-20 01:15:31 +00006618
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006619 // Match up the template parameter lists with the scope specifier, then
6620 // determine whether we have a template or a template specialization.
6621 bool Invalid = false;
Robert Wilhelm1169e2f2013-07-21 15:20:44 +00006622 if (TemplateParameterList *TemplateParams =
6623 MatchTemplateParametersToScopeSpecifier(
6624 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6625 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6626 isExplicitSpecialization, Invalid)) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006627 if (TemplateParams->size() > 0) {
6628 // This is a function template
Abramo Bagnara9b934882010-06-12 08:15:14 +00006629
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006630 // Check that we can declare a template here.
6631 if (CheckTemplateDeclScope(S, TemplateParams))
6632 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006633
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006634 // A destructor cannot be a template.
6635 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6636 Diag(NewFD->getLocation(), diag::err_destructor_template);
6637 return 0;
John McCall5fd378b2010-03-24 08:27:58 +00006638 }
Douglas Gregor20606502011-10-14 15:31:12 +00006639
6640 // If we're adding a template to a dependent context, we may need to
David Blaikied662a792011-10-19 22:56:21 +00006641 // rebuilding some of the types used within the template parameter list,
Douglas Gregor20606502011-10-14 15:31:12 +00006642 // now that we know what the current instantiation is.
6643 if (DC->isDependentContext()) {
6644 ContextRAII SavedContext(*this, DC);
6645 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6646 Invalid = true;
6647 }
6648
John McCall5fd378b2010-03-24 08:27:58 +00006649
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006650 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6651 NewFD->getLocation(),
6652 Name, TemplateParams,
6653 NewFD);
6654 FunctionTemplate->setLexicalDeclContext(CurContext);
6655 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6656
6657 // For source fidelity, store the other template param lists.
6658 if (TemplateParamLists.size() > 1) {
6659 NewFD->setTemplateParameterListsInfo(Context,
6660 TemplateParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00006661 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006662 }
6663 } else {
6664 // This is a function template specialization.
6665 isFunctionTemplateSpecialization = true;
6666 // For source fidelity, store all the template param lists.
6667 NewFD->setTemplateParameterListsInfo(Context,
6668 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006669 TemplateParamLists.data());
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00006670
6671 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6672 if (isFriend) {
6673 // We want to remove the "template<>", found here.
6674 SourceRange RemoveRange = TemplateParams->getSourceRange();
6675
6676 // If we remove the template<> and the name is not a
6677 // template-id, we're actually silently creating a problem:
6678 // the friend declaration will refer to an untemplated decl,
6679 // and clearly the user wants a template specialization. So
6680 // we need to insert '<>' after the name.
6681 SourceLocation InsertLoc;
6682 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6683 InsertLoc = D.getName().getSourceRange().getEnd();
6684 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6685 }
6686
6687 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6688 << Name << RemoveRange
6689 << FixItHint::CreateRemoval(RemoveRange)
6690 << FixItHint::CreateInsertion(InsertLoc, "<>");
6691 }
6692 }
6693 }
6694 else {
6695 // All template param lists were matched against the scope specifier:
6696 // this is NOT (an explicit specialization of) a template.
6697 if (TemplateParamLists.size() > 0)
6698 // For source fidelity, store all the template param lists.
6699 NewFD->setTemplateParameterListsInfo(Context,
6700 TemplateParamLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00006701 TemplateParamLists.data());
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006702 }
6703
6704 if (Invalid) {
6705 NewFD->setInvalidDecl();
6706 if (FunctionTemplate)
6707 FunctionTemplate->setInvalidDecl();
6708 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006709
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006710 // C++ [dcl.fct.spec]p5:
6711 // The virtual specifier shall only be used in declarations of
6712 // nonstatic class member functions that appear within a
6713 // member-specification of a class declaration; see 10.3.
6714 //
6715 if (isVirtual && !NewFD->isInvalidDecl()) {
6716 if (!isVirtualOkay) {
6717 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6718 diag::err_virtual_non_function);
6719 } else if (!CurContext->isRecord()) {
6720 // 'virtual' was specified outside of the class.
Anders Carlssonf1602a52011-01-22 14:43:56 +00006721 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6722 diag::err_virtual_out_of_class)
6723 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6724 } else if (NewFD->getDescribedFunctionTemplate()) {
6725 // C++ [temp.mem]p3:
6726 // A member function template shall not be virtual.
6727 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6728 diag::err_virtual_member_function_template)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006729 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6730 } else {
6731 // Okay: Add virtual to the method.
6732 NewFD->setVirtualAsWritten(true);
John McCall7ad650f2010-03-24 07:46:06 +00006733 }
Richard Smith60e141e2013-05-04 07:00:32 +00006734
6735 if (getLangOpts().CPlusPlus1y &&
6736 NewFD->getResultType()->isUndeducedType())
6737 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00006738 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006739
Richard Smithf93ec762013-11-15 02:58:23 +00006740 if (getLangOpts().CPlusPlus1y &&
6741 (NewFD->isDependentContext() ||
6742 (isFriend && CurContext->isDependentContext())) &&
Richard Smith37e849a2013-08-14 20:16:31 +00006743 NewFD->getResultType()->isUndeducedType()) {
6744 // If the function template is referenced directly (for instance, as a
6745 // member of the current instantiation), pretend it has a dependent type.
6746 // This is not really justified by the standard, but is the only sane
6747 // thing to do.
Richard Smithf93ec762013-11-15 02:58:23 +00006748 // FIXME: For a friend function, we have not marked the function as being
6749 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smith37e849a2013-08-14 20:16:31 +00006750 const FunctionProtoType *FPT =
6751 NewFD->getType()->castAs<FunctionProtoType>();
6752 QualType Result = SubstAutoType(FPT->getResultType(),
6753 Context.DependentTy);
6754 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6755 FPT->getExtProtoInfo()));
6756 }
6757
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006758 // C++ [dcl.fct.spec]p3:
David Blaikied662a792011-10-19 22:56:21 +00006759 // The inline specifier shall not appear on a block scope function
6760 // declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006761 if (isInline && !NewFD->isInvalidDecl()) {
6762 if (CurContext->isFunctionOrMethod()) {
6763 // 'inline' is not allowed on block scope function declaration.
6764 Diag(D.getDeclSpec().getInlineSpecLoc(),
6765 diag::err_inline_declaration_block_scope) << Name
6766 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6767 }
6768 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006769
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006770 // C++ [dcl.fct.spec]p6:
6771 // The explicit specifier shall be used only in the declaration of a
David Blaikied662a792011-10-19 22:56:21 +00006772 // constructor or conversion function within its class definition;
6773 // see 12.3.1 and 12.3.2.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006774 if (isExplicit && !NewFD->isInvalidDecl()) {
6775 if (!CurContext->isRecord()) {
6776 // 'explicit' was specified outside of the class.
6777 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6778 diag::err_explicit_out_of_class)
6779 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6780 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6781 !isa<CXXConversionDecl>(NewFD)) {
6782 // 'explicit' was specified on a function that wasn't a constructor
6783 // or conversion function.
6784 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6785 diag::err_explicit_non_ctor_or_conv_function)
6786 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6787 }
6788 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006789
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006790 if (isConstexpr) {
Richard Smith21c8fa82013-01-14 05:37:29 +00006791 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006792 // are implicitly inline.
6793 NewFD->setImplicitlyInline();
6794
Richard Smith21c8fa82013-01-14 05:37:29 +00006795 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006796 // be either constructors or to return a literal type. Therefore,
6797 // destructors cannot be declared constexpr.
6798 if (isa<CXXDestructorDecl>(NewFD))
Richard Smith9f569cc2011-10-01 02:31:28 +00006799 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006800 }
6801
Douglas Gregor8d267c52011-09-09 02:06:17 +00006802 // If __module_private__ was specified, mark the function accordingly.
6803 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00006804 if (isFunctionTemplateSpecialization) {
6805 SourceLocation ModulePrivateLoc
6806 = D.getDeclSpec().getModulePrivateSpecLoc();
6807 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6808 << 0
6809 << FixItHint::CreateRemoval(ModulePrivateLoc);
6810 } else {
6811 NewFD->setModulePrivate();
6812 if (FunctionTemplate)
6813 FunctionTemplate->setModulePrivate();
6814 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00006815 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006816
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006817 if (isFriend) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006818 if (FunctionTemplate) {
Richard Smith22050f22013-07-17 23:53:16 +00006819 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006820 FunctionTemplate->setAccess(AS_public);
6821 }
Richard Smith22050f22013-07-17 23:53:16 +00006822 NewFD->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006823 NewFD->setAccess(AS_public);
6824 }
6825
Douglas Gregor45fa5602011-11-07 20:56:01 +00006826 // If a function is defined as defaulted or deleted, mark it as such now.
6827 switch (D.getFunctionDefinitionKind()) {
6828 case FDK_Declaration:
6829 case FDK_Definition:
6830 break;
6831
6832 case FDK_Defaulted:
6833 NewFD->setDefaulted();
6834 break;
6835
6836 case FDK_Deleted:
6837 NewFD->setDeletedAsWritten();
6838 break;
6839 }
6840
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006841 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6842 D.isFunctionDefinition()) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00006843 // C++ [class.mfct]p2:
6844 // A member function may be defined (8.4) in its class definition, in
6845 // which case it is an inline member function (7.1.2)
John McCallbfdcdc82010-12-15 04:00:32 +00006846 NewFD->setImplicitlyInline();
6847 }
6848
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006849 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6850 !CurContext->isRecord()) {
6851 // C++ [class.static]p1:
6852 // A data or function member of a class may be declared static
6853 // in a class definition, in which case it is a static member of
6854 // the class.
6855
6856 // Complain about the 'static' specifier if it's on an out-of-line
6857 // member function definition.
6858 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6859 diag::err_static_out_of_line)
6860 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6861 }
Richard Smith444d3842012-10-20 08:26:51 +00006862
6863 // C++11 [except.spec]p15:
6864 // A deallocation function with no exception-specification is treated
6865 // as if it were specified with noexcept(true).
6866 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6867 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6868 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006869 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith444d3842012-10-20 08:26:51 +00006870 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6871 EPI.ExceptionSpecType = EST_BasicNoexcept;
6872 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00006873 FPT->getArgTypes(), EPI));
Richard Smith444d3842012-10-20 08:26:51 +00006874 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00006875 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006876
6877 // Filter out previous declarations that don't match the scope.
Richard Smitha41c97a2013-09-20 01:15:31 +00006878 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006879 isExplicitSpecialization ||
6880 isFunctionTemplateSpecialization);
Richard Smithdd9459f2013-08-13 18:18:50 +00006881
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006882 // Handle GNU asm-label extension (encoded as an attribute).
6883 if (Expr *E = (Expr*) D.getAsmLabel()) {
6884 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00006885 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00006886 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6887 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00006888 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6889 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6890 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6891 if (I != ExtnameUndeclaredIdentifiers.end()) {
6892 NewFD->addAttr(I->second);
6893 ExtnameUndeclaredIdentifiers.erase(I);
6894 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006895 }
6896
Chris Lattner2dbd2852009-04-25 06:12:16 +00006897 // Copy the parameter declarations from the declarator D to the function
6898 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006899 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00006900 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006901 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006902
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006903 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6904 // function that takes no arguments, not a function that takes a
6905 // single void argument.
6906 // We let through "const void" here because Sema::GetTypeForDeclarator
6907 // already checks for that case.
6908 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6909 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006910 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00006911 // Empty arg list, don't push any params.
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006912 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006913 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006914 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00006915 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006916 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6917 Param->setDeclContext(NewFD);
6918 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00006919
6920 if (Param->isInvalidDecl())
6921 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006922 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006923 }
Mike Stump1eb44332009-09-09 15:08:12 +00006924
John McCall183700f2009-09-21 23:43:11 +00006925 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00006926 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006927 // following example, we'll need to synthesize (unnamed)
6928 // parameters for use in the declaration.
6929 //
6930 // @code
6931 // typedef void fn(int);
6932 // fn f;
6933 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00006934
Chris Lattner1ad9b282009-04-25 06:03:53 +00006935 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00006936 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6937 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00006938 ParmVarDecl *Param =
6939 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00006940 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00006941 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006942 }
Chris Lattner84bb9442009-04-25 18:38:18 +00006943 } else {
6944 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6945 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006946 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00006947
Chris Lattner2dbd2852009-04-25 06:12:16 +00006948 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00006949 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00006950
James Molloy16f1f712012-02-29 10:24:19 +00006951 // Find all anonymous symbols defined during the declaration of this function
6952 // and add to NewFD. This lets us track decls such 'enum Y' in:
6953 //
6954 // void f(enum Y {AA} x) {}
6955 //
6956 // which would otherwise incorrectly end up in the translation unit scope.
6957 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6958 DeclsInPrototypeScope.clear();
6959
Richard Smith7586a6e2013-01-30 05:45:05 +00006960 if (D.getDeclSpec().isNoreturnSpecified())
6961 NewFD->addAttr(
6962 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6963 Context));
6964
Richard Smithb03a9df2012-03-13 05:56:40 +00006965 // Functions returning a variably modified type violate C99 6.7.5.2p2
6966 // because all functions have linkage.
6967 if (!NewFD->isInvalidDecl() &&
6968 NewFD->getResultType()->isVariablyModifiedType()) {
6969 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6970 NewFD->setInvalidDecl();
6971 }
6972
Rafael Espindola98ae8342012-05-10 02:50:16 +00006973 // Handle attributes.
Richard Smith4a97b8e2013-08-29 00:47:48 +00006974 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindola98ae8342012-05-10 02:50:16 +00006975
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006976 QualType RetType = NewFD->getResultType();
6977 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6978 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6979 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6980 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006981 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramera32966f2013-10-16 16:21:04 +00006982 // Attach the attribute to the new decl. Don't apply the attribute if it
6983 // returns an instance of the class (e.g. assignment operators).
6984 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006985 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6986 Context));
6987 }
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006988 }
6989
David Blaikie4e4d0842012-03-11 07:00:24 +00006990 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006991 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00006992 bool isExplicitSpecialization=false;
David Majnemerc371db62013-07-06 02:13:46 +00006993 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6994 CheckMain(NewFD, D.getDeclSpec());
6995
David Majnemere9f6f332013-09-16 22:44:20 +00006996 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6997 CheckMSVCRTEntryPoint(NewFD);
6998
David Majnemerc371db62013-07-06 02:13:46 +00006999 if (!NewFD->isInvalidDecl())
Richard Smithb03a9df2012-03-13 05:56:40 +00007000 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7001 isExplicitSpecialization));
Fariborz Jahanian37c765a2012-09-05 17:52:12 +00007002 else if (!Previous.empty())
Richard Smithdd9459f2013-08-13 18:18:50 +00007003 // Make graceful recovery from an invalid redeclaration.
7004 D.setRedeclaration(true);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007005 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007006 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7007 "previous declaration set still overloaded");
7008 } else {
Richard Smithcf19e5b2013-11-16 01:57:09 +00007009 // C++11 [replacement.functions]p3:
7010 // The program's definitions shall not be specified as inline.
7011 //
7012 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7013 //
7014 // Suppress the diagnostic if the function is __attribute__((used)), since
7015 // that forces an external definition to be emitted.
7016 if (D.getDeclSpec().isInlineSpecified() &&
7017 NewFD->isReplaceableGlobalAllocationFunction() &&
7018 !NewFD->hasAttr<UsedAttr>())
7019 Diag(D.getDeclSpec().getInlineSpecLoc(),
7020 diag::ext_operator_new_delete_declared_inline)
7021 << NewFD->getDeclName();
7022
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007023 // If the declarator is a template-id, translate the parser's template
7024 // argument list into our AST format.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007025 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7026 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7027 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7028 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00007029 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007030 TemplateId->NumArgs);
7031 translateTemplateArguments(TemplateArgsPtr,
7032 TemplateArgs);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007033
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007034 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007035
Douglas Gregor89b9f102011-06-06 15:22:55 +00007036 if (NewFD->isInvalidDecl()) {
7037 HasExplicitTemplateArgs = false;
7038 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00007039 // Function template with explicit template arguments.
7040 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7041 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7042
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007043 HasExplicitTemplateArgs = false;
7044 } else if (!isFunctionTemplateSpecialization &&
7045 !D.getDeclSpec().isFriendSpecified()) {
7046 // We have encountered something that the user meant to be a
7047 // specialization (because it has explicitly-specified template
7048 // arguments) but that was not introduced with a "template<>" (or had
7049 // too few of them).
Larisse Voufoef4579c2013-08-06 01:03:05 +00007050 // FIXME: Differentiate between attempts for explicit instantiations
7051 // (starting with "template") and the rest.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007052 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7053 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7054 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00007055 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00007056 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007057 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00007058 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007059 // "friend void foo<>(int);" is an implicit specialization decl.
7060 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00007061 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007062 } else if (isFriend && isFunctionTemplateSpecialization) {
7063 // This combination is only possible in a recovery case; the user
7064 // wrote something like:
7065 // template <> friend void foo(int);
7066 // which we're recovering from as if the user had written:
7067 // friend void foo<>(int);
7068 // Go ahead and fake up a template id.
7069 HasExplicitTemplateArgs = true;
7070 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7071 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007072 }
John McCall29ae6e52010-10-13 05:45:15 +00007073
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007074 // If it's a friend (and only if it's a friend), it's possible
7075 // that either the specialized function type or the specialized
7076 // template is dependent, and therefore matching will fail. In
7077 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007078 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007079 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007080 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7081 TemplateSpecializationType::anyDependentTemplateArguments(
7082 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7083 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007084 assert(HasExplicitTemplateArgs &&
7085 "friend function specialization without template args");
7086 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7087 Previous))
7088 NewFD->setInvalidDecl();
7089 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007090 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00007091 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007092 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00007093 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007094 diag::ext_function_specialization_in_class :
7095 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007096 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007097 } else if (CheckFunctionTemplateSpecialization(NewFD,
7098 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7099 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007100 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00007101
7102 // C++ [dcl.stc]p1:
7103 // A storage-class-specifier shall not be specified in an explicit
7104 // specialization (14.7.3)
Richard Trieu62ab0102013-05-16 02:14:08 +00007105 FunctionTemplateSpecializationInfo *Info =
7106 NewFD->getTemplateSpecializationInfo();
7107 if (Info && SC != SC_None) {
7108 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor0f9dc862011-06-17 05:09:08 +00007109 Diag(NewFD->getLocation(),
7110 diag::err_explicit_specialization_inconsistent_storage_class)
7111 << SC
7112 << FixItHint::CreateRemoval(
7113 D.getDeclSpec().getStorageClassSpecLoc());
7114
7115 else
7116 Diag(NewFD->getLocation(),
7117 diag::ext_explicit_specialization_storage_class)
7118 << FixItHint::CreateRemoval(
7119 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00007120 }
7121
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007122 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7123 if (CheckMemberSpecialization(NewFD, Previous))
7124 NewFD->setInvalidDecl();
7125 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007126
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007127 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00007128 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemerc371db62013-07-06 02:13:46 +00007129 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7130 CheckMain(NewFD, D.getDeclSpec());
7131
David Majnemere9f6f332013-09-16 22:44:20 +00007132 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7133 CheckMSVCRTEntryPoint(NewFD);
7134
David Blaikie14068e82011-09-08 06:33:04 +00007135 if (NewFD->isInvalidDecl()) {
7136 // If this is a class member, mark the class invalid immediately.
7137 // This avoids some consistency errors later.
7138 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7139 methodDecl->getParent()->setInvalidDecl();
David Majnemerc371db62013-07-06 02:13:46 +00007140 } else
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007141 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7142 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00007143 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007144
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007145 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007146 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7147 "previous declaration set still overloaded");
7148
7149 NamedDecl *PrincipalDecl = (FunctionTemplate
7150 ? cast<NamedDecl>(FunctionTemplate)
7151 : NewFD);
7152
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007153 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007154 AccessSpecifier Access = AS_public;
7155 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00007156 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007157
7158 NewFD->setAccess(Access);
7159 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007160 }
7161
7162 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7163 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7164 PrincipalDecl->setNonMemberOperator();
7165
7166 // If we have a function template, check the template parameter
7167 // list. This will check and merge default template arguments.
7168 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00007169 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00007170 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007171 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00007172 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00007173 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007174 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00007175 ? TPC_FriendFunctionTemplateDefinition
7176 : TPC_FriendFunctionTemplate)
7177 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00007178 DC && DC->isRecord() &&
7179 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00007180 ? TPC_ClassTemplateMember
7181 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007182 }
7183
7184 if (NewFD->isInvalidDecl()) {
7185 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007186 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00007187 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007188 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007189 // Fake up an access specifier if it's supposed to be a class member.
7190 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7191 NewFD->setAccess(AS_public);
7192
7193 // Qualified decls generally require a previous declaration.
7194 if (D.getCXXScopeSpec().isSet()) {
7195 // ...with the major exception of templated-scope or
7196 // dependent-scope friend declarations.
7197
7198 // TODO: we currently also suppress this check in dependent
7199 // contexts because (1) the parameter depth will be off when
7200 // matching friend templates and (2) we might actually be
7201 // selecting a friend based on a dependent factor. But there
7202 // are situations where these conditions don't apply and we
7203 // can actually do this check immediately.
7204 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007205 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007206 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7207 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007208 // ignore these
7209 } else {
7210 // The user tried to provide an out-of-line definition for a
7211 // function that is a member of a class or namespace, but there
7212 // was no such member function declared (C++ [class.mfct]p2,
7213 // C++ [namespace.memdef]p2). For example:
7214 //
7215 // class X {
7216 // void f() const;
7217 // };
7218 //
7219 // void X::f() { } // ill-formed
7220 //
7221 // Complain about this problem, and attempt to suggest close
7222 // matches (e.g., those that differ only in cv-qualifiers and
7223 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007224
Richard Smith4e9686b2013-08-09 04:35:01 +00007225 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7226 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007227 AddToScope = ExtraArgs.AddToScope;
7228 return Result;
7229 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007230 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007231
7232 // Unqualified local friend declarations are required to resolve
7233 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007234 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith4e9686b2013-08-09 04:35:01 +00007235 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7236 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007237 AddToScope = ExtraArgs.AddToScope;
7238 return Result;
7239 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007240 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007241
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007242 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007243 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00007244 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007245 // An out-of-line member function declaration must also be a
7246 // definition (C++ [dcl.meaning]p1).
7247 // Note that this is not the case for explicit specializations of
7248 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00007249 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7250 // extension for compatibility with old SWIG code which likes to
7251 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007252 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7253 << D.getCXXScopeSpec().getRange();
7254 }
7255 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00007256
Rafael Espindola65611bf2013-03-02 21:41:48 +00007257 ProcessPragmaWeak(S, NewFD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00007258 checkAttributesAfterMerging(*this, *NewFD);
7259
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007260 AddKnownFunctionAttributes(NewFD);
7261
Douglas Gregord9455382010-08-06 13:50:58 +00007262 if (NewFD->hasAttr<OverloadableAttr>() &&
7263 !NewFD->getType()->getAs<FunctionProtoType>()) {
7264 Diag(NewFD->getLocation(),
7265 diag::err_attribute_overloadable_no_prototype)
7266 << NewFD;
7267
7268 // Turn this into a variadic function with no parameters.
7269 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckneref072032013-08-27 23:08:25 +00007270 FunctionProtoType::ExtProtoInfo EPI(
7271 Context.getDefaultCallingConvention(true, false));
John McCalle23cf432010-12-14 08:05:40 +00007272 EPI.Variadic = true;
7273 EPI.ExtInfo = FT->getExtInfo();
7274
Dmitri Gribenko55431692013-05-05 00:41:58 +00007275 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00007276 NewFD->setType(R);
7277 }
7278
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007279 // If there's a #pragma GCC visibility in scope, and this isn't a class
7280 // member, set the visibility of this function.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007281 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007282 AddPushedVisibilityAttribute(NewFD);
7283
John McCall8dfac0b2011-09-30 05:12:12 +00007284 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7285 // marking the function.
7286 AddCFAuditedAttribute(NewFD);
7287
Richard Smithaa4bc182013-06-30 09:48:50 +00007288 // If this is the first declaration of an extern C variable, update
7289 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00007290 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00007291 isIncompleteDeclExternC(*this, NewFD))
Richard Smith662f41b2013-06-18 20:15:12 +00007292 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007293
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007294 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007295 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007296
David Blaikie4e4d0842012-03-11 07:00:24 +00007297 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007298 if (FunctionTemplate) {
7299 if (NewFD->isInvalidDecl())
7300 FunctionTemplate->setInvalidDecl();
7301 return FunctionTemplate;
7302 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007303 }
Mike Stump1eb44332009-09-09 15:08:12 +00007304
Guy Benyeie6b9d802013-01-20 12:31:11 +00007305 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyeie6b9d802013-01-20 12:31:11 +00007306 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7307 if ((getLangOpts().OpenCLVersion >= 120)
7308 && (SC == SC_Static)) {
7309 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7310 D.setInvalidType();
7311 }
Tanya Lattner7564bcc2013-01-30 19:48:52 +00007312
7313 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7314 if (!NewFD->getResultType()->isVoidType()) {
7315 Diag(D.getIdentifierLoc(),
7316 diag::err_expected_kernel_void_return_type);
7317 D.setInvalidType();
7318 }
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007319
7320 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007321 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7322 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly98f988d2013-01-29 10:54:06 +00007323 ParmVarDecl *Param = *PI;
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007324 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyeie6b9d802013-01-20 12:31:11 +00007325 }
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00007326 }
7327
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00007328 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007329
David Blaikie4e4d0842012-03-11 07:00:24 +00007330 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007331 if (IdentifierInfo *II = NewFD->getIdentifier())
7332 if (!NewFD->isInvalidDecl() &&
7333 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7334 if (II->isStr("cudaConfigureCall")) {
7335 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7336 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7337
7338 Context.setcudaConfigureCallDecl(NewFD);
7339 }
7340 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007341
7342 // Here we have an function template explicit specialization at class scope.
7343 // The actually specialization will be postponed to template instatiation
7344 // time via the ClassScopeFunctionSpecializationDecl node.
7345 if (isDependentClassScopeExplicitSpecialization) {
7346 ClassScopeFunctionSpecializationDecl *NewSpec =
7347 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber6b020092012-06-25 17:21:05 +00007348 Context, CurContext, SourceLocation(),
7349 cast<CXXMethodDecl>(NewFD),
7350 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007351 CurContext->addDecl(NewSpec);
7352 AddToScope = false;
7353 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007354
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007355 return NewFD;
7356}
7357
7358/// \brief Perform semantic checking of a new function declaration.
7359///
7360/// Performs semantic analysis of the new function declaration
7361/// NewFD. This routine performs all semantic checking that does not
7362/// require the actual declarator involved in the declaration, and is
7363/// used both for the declaration of functions as they are parsed
7364/// (called via ActOnDeclarator) and for the declaration of functions
7365/// that have been instantiated via C++ template instantiation (called
7366/// via InstantiateDecl).
7367///
James Dennettefce31f2012-06-22 08:10:18 +00007368/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorfd056bc2009-10-13 16:30:37 +00007369/// an explicit specialization of the previous declaration.
7370///
Chris Lattnereaaebc72009-04-25 08:06:05 +00007371/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007372///
James Dennettefce31f2012-06-22 08:10:18 +00007373/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007374bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00007375 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007376 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00007377 assert(!NewFD->getResultType()->isVariablyModifiedType()
7378 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00007379
Richard Smithdd9459f2013-08-13 18:18:50 +00007380 // Determine whether the type of this function should be merged with
7381 // a previous visible declaration. This never happens for functions in C++,
7382 // and always happens in C if the previous declaration was visible.
7383 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7384 !Previous.isShadowed();
7385
Douglas Gregor7dc80e12013-01-09 00:47:56 +00007386 // Filter out any non-conflicting previous declarations.
7387 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7388
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007389 bool Redeclaration = false;
Richard Smith21c8fa82013-01-14 05:37:29 +00007390 NamedDecl *OldDecl = 0;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007391
Douglas Gregor04495c82009-02-24 01:23:02 +00007392 // Merge or overload the declaration with an existing declaration of
7393 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00007394 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00007395 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007396 // a declaration that requires merging. If it's an overload,
7397 // there's no more work to do here; we'll just add the new
7398 // function to the scope.
John McCall871b2e72009-12-09 03:35:25 +00007399 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola90cc3902013-04-15 12:49:13 +00007400 NamedDecl *Candidate = Previous.getFoundDecl();
7401 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7402 Redeclaration = true;
7403 OldDecl = Candidate;
7404 }
John McCall871b2e72009-12-09 03:35:25 +00007405 } else {
John McCallad00b772010-06-16 08:42:20 +00007406 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7407 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00007408 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007409 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00007410 break;
7411
7412 case Ovl_NonFunction:
7413 Redeclaration = true;
7414 break;
7415
7416 case Ovl_Overload:
7417 Redeclaration = false;
7418 break;
John McCall68263142009-11-18 22:49:29 +00007419 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00007420
David Blaikie4e4d0842012-03-11 07:00:24 +00007421 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00007422 // If a function name is overloadable in C, then every function
7423 // with that name must be marked "overloadable".
7424 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7425 << Redeclaration << NewFD;
7426 NamedDecl *OverloadedDecl = 0;
7427 if (Redeclaration)
7428 OverloadedDecl = OldDecl;
7429 else if (!Previous.empty())
7430 OverloadedDecl = Previous.getRepresentativeDecl();
7431 if (OverloadedDecl)
7432 Diag(OverloadedDecl->getLocation(),
7433 diag::note_attribute_overloadable_prev_overload);
7434 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7435 Context));
7436 }
John McCall68263142009-11-18 22:49:29 +00007437 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007438 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007439
Richard Smithaa4bc182013-06-30 09:48:50 +00007440 // Check for a previous extern "C" declaration with this name.
7441 if (!Redeclaration &&
7442 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7443 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7444 if (!Previous.empty()) {
7445 // This is an extern "C" declaration with the same name as a previous
7446 // declaration, and thus redeclares that entity...
7447 Redeclaration = true;
7448 OldDecl = Previous.getFoundDecl();
Richard Smithdd9459f2013-08-13 18:18:50 +00007449 MergeTypeWithPrevious = false;
Richard Smithaa4bc182013-06-30 09:48:50 +00007450
7451 // ... except in the presence of __attribute__((overloadable)).
7452 if (OldDecl->hasAttr<OverloadableAttr>()) {
7453 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7454 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7455 << Redeclaration << NewFD;
7456 Diag(Previous.getFoundDecl()->getLocation(),
7457 diag::note_attribute_overloadable_prev_overload);
7458 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7459 Context));
7460 }
7461 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7462 Redeclaration = false;
7463 OldDecl = 0;
7464 }
7465 }
7466 }
7467 }
7468
Richard Smith21c8fa82013-01-14 05:37:29 +00007469 // C++11 [dcl.constexpr]p8:
7470 // A constexpr specifier for a non-static member function that is not
7471 // a constructor declares that member function to be const.
7472 //
7473 // This needs to be delayed until we know whether this is an out-of-line
7474 // definition of a static member function.
Richard Smith84046262013-04-21 01:08:50 +00007475 //
7476 // This rule is not present in C++1y, so we produce a backwards
7477 // compatibility warning whenever it happens in C++11.
Richard Smith21c8fa82013-01-14 05:37:29 +00007478 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith84046262013-04-21 01:08:50 +00007479 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7480 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith21c8fa82013-01-14 05:37:29 +00007481 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7482 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7483 if (FunctionTemplateDecl *OldTD =
7484 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7485 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7486 if (!OldMD || !OldMD->isStatic()) {
7487 const FunctionProtoType *FPT =
7488 MD->getType()->castAs<FunctionProtoType>();
7489 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7490 EPI.TypeQuals |= Qualifiers::Const;
7491 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00007492 FPT->getArgTypes(), EPI));
Richard Smith84046262013-04-21 01:08:50 +00007493
7494 // Warn that we did this, if we're not performing template instantiation.
7495 // In that case, we'll have warned already when the template was defined.
7496 if (ActiveTemplateInstantiations.empty()) {
7497 SourceLocation AddConstLoc;
7498 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7499 .IgnoreParens().getAs<FunctionTypeLoc>())
7500 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7501
7502 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7503 << FixItHint::CreateInsertion(AddConstLoc, " const");
7504 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007505 }
7506 }
7507
7508 if (Redeclaration) {
7509 // NewFD and OldDecl represent declarations that need to be
7510 // merged.
Richard Smithdd9459f2013-08-13 18:18:50 +00007511 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith21c8fa82013-01-14 05:37:29 +00007512 NewFD->setInvalidDecl();
7513 return Redeclaration;
7514 }
7515
7516 Previous.clear();
7517 Previous.addDecl(OldDecl);
7518
7519 if (FunctionTemplateDecl *OldTemplateDecl
7520 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7521 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7522 FunctionTemplateDecl *NewTemplateDecl
7523 = NewFD->getDescribedFunctionTemplate();
7524 assert(NewTemplateDecl && "Template/non-template mismatch");
7525 if (CXXMethodDecl *Method
7526 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7527 Method->setAccess(OldTemplateDecl->getAccess());
7528 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007529 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007530
7531 // If this is an explicit specialization of a member that is a function
7532 // template, mark it as a member specialization.
7533 if (IsExplicitSpecialization &&
7534 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7535 NewTemplateDecl->setMemberSpecialization();
7536 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00007537 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007538
7539 } else {
John McCalld5617ee2013-01-25 22:31:03 +00007540 // This needs to happen first so that 'inline' propagates.
Richard Smith21c8fa82013-01-14 05:37:29 +00007541 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCalld5617ee2013-01-25 22:31:03 +00007542
7543 if (isa<CXXMethodDecl>(NewFD)) {
7544 // A valid redeclaration of a C++ method must be out-of-line,
7545 // but (unfortunately) it's not necessarily a definition
7546 // because of templates, which means that the previous
7547 // declaration is not necessarily from the class definition.
7548
7549 // For just setting the access, that doesn't matter.
7550 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7551 NewFD->setAccess(oldMethod->getAccess());
7552
7553 // Update the key-function state if necessary for this ABI.
7554 if (NewFD->isInlined() &&
7555 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7556 // setNonKeyFunction needs to work with the original
7557 // declaration from the class definition, and isVirtual() is
7558 // just faster in that case, so map back to that now.
Rafael Espindolabc650912013-10-17 15:37:26 +00007559 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCalld5617ee2013-01-25 22:31:03 +00007560 if (oldMethod->isVirtual()) {
7561 Context.setNonKeyFunction(oldMethod);
7562 }
7563 }
7564 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007565 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00007566 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007567
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007568 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00007569 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007570 // C++-specific checks.
7571 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7572 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00007573 } else if (CXXDestructorDecl *Destructor =
7574 dyn_cast<CXXDestructorDecl>(NewFD)) {
7575 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007576 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00007577
Douglas Gregor4923aa22010-07-02 20:37:36 +00007578 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00007579 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007580 if (!ClassType->isDependentType()) {
7581 DeclarationName Name
7582 = Context.DeclarationNames.getCXXDestructorName(
7583 Context.getCanonicalType(ClassType));
7584 if (NewFD->getDeclName() != Name) {
7585 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007586 NewFD->setInvalidDecl();
7587 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007588 }
7589 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007590 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00007591 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007592 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00007593 }
7594
7595 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00007596 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7597 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00007598 !Method->getDescribedFunctionTemplate() &&
7599 Method->isCanonicalDecl()) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007600 if (AddOverriddenMethods(Method->getParent(), Method)) {
7601 // If the function was marked as "static", we have a problem.
7602 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie5708c182012-10-17 00:47:58 +00007603 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007604 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00007605 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007606 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007607
7608 if (Method->isStatic())
7609 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00007610 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007611
7612 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7613 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007614 CheckOverloadedOperatorDeclaration(NewFD)) {
7615 NewFD->setInvalidDecl();
7616 return Redeclaration;
7617 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007618
7619 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7620 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007621 CheckLiteralOperatorDeclaration(NewFD)) {
7622 NewFD->setInvalidDecl();
7623 return Redeclaration;
7624 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007625
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007626 // In C++, check default arguments now that we have merged decls. Unless
7627 // the lexical context is the class, because in this case this is done
7628 // during delayed parsing anyway.
7629 if (!CurContext->isRecord())
7630 CheckCXXDefaultArguments(NewFD);
Warren Hunt2d023ec2013-11-01 23:46:51 +00007631
Douglas Gregorb68e3992010-12-21 19:47:46 +00007632 // If this function declares a builtin function, check the type of this
7633 // declaration against the expected type for the builtin.
7634 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7635 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanian9ef15182013-01-05 21:54:55 +00007636 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregorb68e3992010-12-21 19:47:46 +00007637 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7638 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7639 // The type of this function differs from the type of the builtin,
7640 // so forget about the builtin entirely.
7641 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7642 }
7643 }
Warren Hunt2d023ec2013-11-01 23:46:51 +00007644
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007645 // If this function is declared as being extern "C", then check to see if
7646 // the function returns a UDT (class, struct, or union type) that is not C
7647 // compatible, and if it does, warn the user.
Fariborz Jahanian96db3292013-03-14 23:09:00 +00007648 // But, issue any diagnostic on the first declaration only.
7649 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007650 QualType R = NewFD->getResultType();
Hans Wennborg168c07b2012-07-24 17:59:41 +00007651 if (R->isIncompleteType() && !R->isVoidType())
7652 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7653 << NewFD << R;
Douglas Gregorb38b4912012-08-07 06:14:34 +00007654 else if (!R.isPODType(Context) && !R->isVoidType() &&
7655 !R->isObjCObjectPointerType())
Hans Wennborg168c07b2012-07-24 17:59:41 +00007656 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007657 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007658 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007659 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007660}
7661
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007662static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7663 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7664 if (!TSI)
7665 return SourceRange();
7666
7667 TypeLoc TL = TSI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00007668 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007669 if (!FunctionTL)
7670 return SourceRange();
7671
David Blaikie39e6ab42013-02-18 22:06:02 +00007672 TypeLoc ResultTL = FunctionTL.getResultLoc();
7673 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007674 return ResultTL.getSourceRange();
7675
7676 return SourceRange();
7677}
7678
David Blaikie14068e82011-09-08 06:33:04 +00007679void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00007680 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7681 // static or constexpr is ill-formed.
Richard Smithde03c152013-01-17 22:16:11 +00007682 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7683 // appear in a declaration of main.
John McCall13591ed2009-07-25 04:36:53 +00007684 // static main is not an error under C99, but we should warn about it.
Richard Smithde03c152013-01-17 22:16:11 +00007685 // We accept _Noreturn main as an extension.
David Blaikie14068e82011-09-08 06:33:04 +00007686 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00007687 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00007688 ? diag::err_static_main : diag::warn_static_main)
7689 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7690 if (FD->isInlineSpecified())
7691 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7692 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko445743d2013-01-21 11:25:03 +00007693 if (DS.isNoreturnSpecified()) {
7694 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7695 SourceRange NoreturnRange(NoreturnLoc,
7696 PP.getLocForEndOfToken(NoreturnLoc));
7697 Diag(NoreturnLoc, diag::ext_noreturn_main);
7698 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7699 << FixItHint::CreateRemoval(NoreturnRange);
7700 }
Richard Smitha5065862012-02-04 06:10:17 +00007701 if (FD->isConstexpr()) {
7702 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7703 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7704 FD->setConstexpr(false);
7705 }
John McCall13591ed2009-07-25 04:36:53 +00007706
Joey Goulyc879fe52013-11-05 12:30:39 +00007707 if (getLangOpts().OpenCL) {
7708 Diag(FD->getLocation(), diag::err_opencl_no_main)
7709 << FD->hasAttr<OpenCLKernelAttr>();
7710 FD->setInvalidDecl();
7711 return;
7712 }
7713
John McCall13591ed2009-07-25 04:36:53 +00007714 QualType T = FD->getType();
7715 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00007716 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007717
John McCall75d8ba32012-02-14 19:50:52 +00007718 // All the standards say that main() should should return 'int'.
7719 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7720 // In C and C++, main magically returns 0 if you fall off the end;
7721 // set the flag which tells us that.
7722 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7723 FD->setHasImplicitReturnZero(true);
7724
7725 // In C with GNU extensions we allow main() to have non-integer return
7726 // type, but we should warn about the extension, and we disable the
7727 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00007728 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00007729 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7730
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007731 SourceRange ResultRange = getResultSourceRange(FD);
7732 if (ResultRange.isValid())
7733 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7734 << FixItHint::CreateReplacement(ResultRange, "int");
7735
John McCall75d8ba32012-02-14 19:50:52 +00007736 // Otherwise, this is just a flat-out error.
7737 } else {
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007738 SourceRange ResultRange = getResultSourceRange(FD);
7739 if (ResultRange.isValid())
7740 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7741 << FixItHint::CreateReplacement(ResultRange, "int");
7742 else
7743 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7744
John McCall13591ed2009-07-25 04:36:53 +00007745 FD->setInvalidDecl(true);
7746 }
7747
7748 // Treat protoless main() as nullary.
7749 if (isa<FunctionNoProtoType>(FT)) return;
7750
7751 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7752 unsigned nparams = FTP->getNumArgs();
7753 assert(FD->getNumParams() == nparams);
7754
John McCall66755862009-12-24 09:58:38 +00007755 bool HasExtraParameters = (nparams > 3);
7756
7757 // Darwin passes an undocumented fourth argument of type char**. If
7758 // other platforms start sprouting these, the logic below will start
7759 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007760 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00007761 HasExtraParameters = false;
7762
7763 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00007764 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7765 FD->setInvalidDecl(true);
7766 nparams = 3;
7767 }
7768
7769 // FIXME: a lot of the following diagnostics would be improved
7770 // if we had some location information about types.
7771
7772 QualType CharPP =
7773 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00007774 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00007775
7776 for (unsigned i = 0; i < nparams; ++i) {
7777 QualType AT = FTP->getArgType(i);
7778
7779 bool mismatch = true;
7780
7781 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7782 mismatch = false;
7783 else if (Expected[i] == CharPP) {
7784 // As an extension, the following forms are okay:
7785 // char const **
7786 // char const * const *
7787 // char * const *
7788
John McCall0953e762009-09-24 19:53:00 +00007789 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00007790 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00007791 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7792 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith485b3122013-01-29 02:49:47 +00007793 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7794 Context.CharTy)) {
John McCall13591ed2009-07-25 04:36:53 +00007795 qs.removeConst();
7796 mismatch = !qs.empty();
7797 }
7798 }
7799
7800 if (mismatch) {
7801 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7802 // TODO: suggest replacing given type with expected type
7803 FD->setInvalidDecl(true);
7804 }
7805 }
7806
7807 if (nparams == 1 && !FD->isInvalidDecl()) {
7808 Diag(FD->getLocation(), diag::warn_main_one_arg);
7809 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007810
7811 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemere9f6f332013-09-16 22:44:20 +00007812 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7813 FD->setInvalidDecl();
7814 }
7815}
7816
7817void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7818 QualType T = FD->getType();
7819 assert(T->isFunctionType() && "function decl is not of function type");
7820 const FunctionType *FT = T->castAs<FunctionType>();
7821
7822 // Set an implicit return of 'zero' if the function can return some integral,
7823 // enumeration, pointer or nullptr type.
7824 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7825 FT->getResultType()->isAnyPointerType() ||
7826 FT->getResultType()->isNullPtrType())
7827 // DllMain is exempt because a return value of zero means it failed.
7828 if (FD->getName() != "DllMain")
7829 FD->setHasImplicitReturnZero(true);
7830
7831 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7832 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007833 FD->setInvalidDecl();
7834 }
John McCall8c4859a2009-07-24 03:03:21 +00007835}
7836
Eli Friedmanc594b322008-05-20 13:48:25 +00007837bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007838 // FIXME: Need strict checking. In C89, we need to check for
7839 // any assignment, increment, decrement, function-calls, or
7840 // commas outside of a sizeof. In C99, it's the same list,
7841 // except that the aforementioned are allowed in unevaluated
7842 // expressions. Everything else falls under the
7843 // "may accept other forms of constant expressions" exception.
7844 // (We never end up here for C++, so the constant expression
7845 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00007846 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00007847 return false;
Eli Friedman21298282009-02-26 04:47:58 +00007848 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7849 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00007850 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00007851}
7852
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007853namespace {
7854 // Visits an initialization expression to see if OrigDecl is evaluated in
7855 // its own initialization and throws a warning if it does.
7856 class SelfReferenceChecker
7857 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7858 Sema &S;
7859 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00007860 bool isRecordType;
7861 bool isPODType;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007862 bool isReferenceType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007863
7864 public:
7865 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7866
7867 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00007868 S(S), OrigDecl(OrigDecl) {
7869 isPODType = false;
7870 isRecordType = false;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007871 isReferenceType = false;
Richard Trieu898267f2011-09-01 21:44:13 +00007872 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7873 isPODType = VD->getType().isPODType(S.Context);
7874 isRecordType = VD->getType()->isRecordType();
Hans Wennborg8be9e772012-08-17 10:12:33 +00007875 isReferenceType = VD->getType()->isReferenceType();
Richard Trieu898267f2011-09-01 21:44:13 +00007876 }
7877 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007878
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007879 // For most expressions, the cast is directly above the DeclRefExpr.
7880 // For conditional operators, the cast can be outside the conditional
7881 // operator if both expressions are DeclRefExpr's.
7882 void HandleValue(Expr *E) {
Richard Trieu568f7852012-10-01 17:39:51 +00007883 if (isReferenceType)
7884 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007885 E = E->IgnoreParenImpCasts();
7886 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7887 HandleDeclRefExpr(DRE);
7888 return;
7889 }
7890
7891 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7892 HandleValue(CO->getTrueExpr());
7893 HandleValue(CO->getFalseExpr());
Richard Trieu6b2cc422012-10-03 00:41:36 +00007894 return;
7895 }
7896
7897 if (isa<MemberExpr>(E)) {
7898 Expr *Base = E->IgnoreParenImpCasts();
7899 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7900 // Check for static member variables and don't warn on them.
7901 if (!isa<FieldDecl>(ME->getMemberDecl()))
7902 return;
7903 Base = ME->getBase()->IgnoreParenImpCasts();
7904 }
7905 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7906 HandleDeclRefExpr(DRE);
7907 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007908 }
7909 }
7910
Richard Trieu568f7852012-10-01 17:39:51 +00007911 // Reference types are handled here since all uses of references are
7912 // bad, not just r-value uses.
7913 void VisitDeclRefExpr(DeclRefExpr *E) {
7914 if (isReferenceType)
7915 HandleDeclRefExpr(E);
7916 }
7917
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007918 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu6b2cc422012-10-03 00:41:36 +00007919 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007920 (isRecordType && E->getCastKind() == CK_NoOp))
7921 HandleValue(E->getSubExpr());
7922
7923 Inherited::VisitImplicitCastExpr(E);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007924 }
7925
Richard Trieu898267f2011-09-01 21:44:13 +00007926 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007927 // Don't warn on arrays since they can be treated as pointers.
Richard Trieu47eb8982011-09-07 00:58:53 +00007928 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007929
Richard Trieu6b2cc422012-10-03 00:41:36 +00007930 // Warn when a non-static method call is followed by non-static member
7931 // field accesses, which is followed by a DeclRefExpr.
7932 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7933 bool Warn = (MD && !MD->isStatic());
7934 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7935 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7936 if (!isa<FieldDecl>(ME->getMemberDecl()))
7937 Warn = false;
7938 Base = ME->getBase()->IgnoreParenImpCasts();
7939 }
Richard Trieu898267f2011-09-01 21:44:13 +00007940
Richard Trieu6b2cc422012-10-03 00:41:36 +00007941 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7942 if (Warn)
7943 HandleDeclRefExpr(DRE);
7944 return;
7945 }
7946
7947 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7948 // Visit that expression.
7949 Visit(Base);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007950 }
7951
Richard Trieu8af742a2013-03-26 03:41:40 +00007952 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7953 if (E->getNumArgs() > 0)
7954 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7955 HandleDeclRefExpr(DRE);
7956
7957 Inherited::VisitCXXOperatorCallExpr(E);
7958 }
7959
Richard Trieu898267f2011-09-01 21:44:13 +00007960 void VisitUnaryOperator(UnaryOperator *E) {
7961 // For POD record types, addresses of its own members are well-defined.
Richard Trieu6b2cc422012-10-03 00:41:36 +00007962 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7963 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7964 if (!isPODType)
7965 HandleValue(E->getSubExpr());
7966 return;
7967 }
Richard Trieu898267f2011-09-01 21:44:13 +00007968 Inherited::VisitUnaryOperator(E);
Richard Smith0f2fc5f2013-05-03 19:16:22 +00007969 }
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007970
7971 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7972
Richard Trieu898267f2011-09-01 21:44:13 +00007973 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumif3052792013-01-19 01:54:35 +00007974 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007975 if (OrigDecl != ReferenceDecl) return;
Ted Kremenek39371b82013-01-19 04:33:14 +00007976 unsigned diag;
7977 if (isReferenceType) {
7978 diag = diag::warn_uninit_self_reference_in_reference_init;
7979 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7980 diag = diag::warn_static_self_reference_in_init;
7981 } else {
7982 diag = diag::warn_uninit_self_reference_in_init;
7983 }
7984
Richard Trieu898267f2011-09-01 21:44:13 +00007985 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborg5965b7c2012-08-20 08:52:22 +00007986 S.PDiag(diag)
Hans Wennborg7821e072012-09-21 08:58:33 +00007987 << DRE->getNameInfo().getName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00007988 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00007989 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007990 }
7991 };
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007992
Richard Trieu568f7852012-10-01 17:39:51 +00007993 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7994 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7995 bool DirectInit) {
7996 // Parameters arguments are occassionially constructed with itself,
7997 // for instance, in recursive functions. Skip them.
7998 if (isa<ParmVarDecl>(OrigDecl))
7999 return;
8000
8001 E = E->IgnoreParens();
8002
8003 // Skip checking T a = a where T is not a record or reference type.
8004 // Doing so is a way to silence uninitialized warnings.
8005 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8006 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8007 if (ICE->getCastKind() == CK_LValueToRValue)
8008 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8009 if (DRE->getDecl() == OrigDecl)
8010 return;
8011
8012 SelfReferenceChecker(S, OrigDecl).Visit(E);
8013 }
Richard Trieu898267f2011-09-01 21:44:13 +00008014}
8015
Douglas Gregor09f41cf2009-01-14 15:45:31 +00008016/// AddInitializerToDecl - Adds the initializer Init to the
8017/// declaration dcl. If DirectInit is true, this is C++ direct
8018/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00008019void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8020 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008021 // If there is no declaration, there was an error parsing it. Just ignore
8022 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00008023 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008025
Douglas Gregor021c3b32009-03-11 23:00:04 +00008026 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8027 // With declarators parsed the way they are, the parser cannot
8028 // distinguish between a normal initializer and a pure-specifier.
8029 // Thus this grotesque test.
8030 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00008031 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00008032 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8033 CheckPureMethod(Method, Init->getSourceRange());
8034 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00008035 Diag(Method->getLocation(), diag::err_member_function_initialization)
8036 << Method->getDeclName() << Init->getSourceRange();
8037 Method->setInvalidDecl();
8038 }
8039 return;
8040 }
8041
Steve Naroff410e3e22007-09-12 20:13:48 +00008042 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8043 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00008044 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8045 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00008046 RealDecl->setInvalidDecl();
8047 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00008048 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008049 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8050
Richard Smith01888722011-12-15 19:20:59 +00008051 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00008052 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008053 Expr *DeduceInit = Init;
8054 // Initializer could be a C++ direct-initializer. Deduction only works if it
8055 // contains exactly one expression.
8056 if (CXXDirectInit) {
8057 if (CXXDirectInit->getNumExprs() == 0) {
8058 // It isn't possible to write this directly, but it is possible to
8059 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00008060 Diag(CXXDirectInit->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008061 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8062 : diag::err_auto_var_init_no_expression)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008063 << VDecl->getDeclName() << VDecl->getType()
8064 << VDecl->getSourceRange();
8065 RealDecl->setInvalidDecl();
8066 return;
8067 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00008068 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008069 VDecl->isInitCapture()
8070 ? diag::err_init_capture_multiple_expressions
8071 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008072 << VDecl->getDeclName() << VDecl->getType()
8073 << VDecl->getSourceRange();
8074 RealDecl->setInvalidDecl();
8075 return;
8076 } else {
8077 DeduceInit = CXXDirectInit->getExpr(0);
8078 }
8079 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008080
8081 // Expressions default to 'id' when we're in a debugger.
8082 bool DefaultedToAuto = false;
8083 if (getLangOpts().DebuggerCastResultToId &&
8084 Init->getType() == Context.UnknownAnyTy) {
8085 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8086 if (Result.isInvalid()) {
8087 VDecl->setInvalidDecl();
8088 return;
8089 }
8090 Init = Result.take();
8091 DefaultedToAuto = true;
8092 }
Richard Smith9b131752013-04-30 21:23:01 +00008093
8094 QualType DeducedType;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008095 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00008096 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008097 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9b131752013-04-30 21:23:01 +00008098 if (DeducedType.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008099 RealDecl->setInvalidDecl();
8100 return;
8101 }
Richard Smith9b131752013-04-30 21:23:01 +00008102 VDecl->setType(DeducedType);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00008103 assert(VDecl->isLinkageValid());
Rafael Espindola2d9e8832013-03-12 21:06:00 +00008104
John McCallf85e1932011-06-15 23:02:42 +00008105 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00008106 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00008107 VDecl->setInvalidDecl();
8108
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008109 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8110 // 'id' instead of a specific object type prevents most of our usual checks.
8111 // We only want to warn outside of template instantiations, though:
8112 // inside a template, the 'id' could have come from a parameter.
Douglas Gregor1344e942013-03-07 22:57:58 +00008113 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith9b131752013-04-30 21:23:01 +00008114 DeducedType->isObjCIdType()) {
8115 SourceLocation Loc =
8116 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008117 Diag(Loc, diag::warn_auto_var_is_id)
8118 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8119 }
8120
Richard Smith34b41d92011-02-20 03:19:35 +00008121 // If this is a redeclaration, check that the type we just deduced matches
8122 // the previously declared type.
Richard Smithdd9459f2013-08-13 18:18:50 +00008123 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8124 // We never need to merge the type, because we cannot form an incomplete
8125 // array of auto, nor deduce such a type.
8126 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8127 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00008128
8129 // Check the deduced type is valid for a variable declaration.
8130 CheckVariableDeclarationType(VDecl);
8131 if (VDecl->isInvalidDecl())
8132 return;
Richard Smith34b41d92011-02-20 03:19:35 +00008133 }
Richard Smith01888722011-12-15 19:20:59 +00008134
8135 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8136 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8137 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8138 VDecl->setInvalidDecl();
8139 return;
8140 }
8141
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008142 if (!VDecl->getType()->isDependentType()) {
8143 // A definition must end up with a complete type, which means it must be
8144 // complete with the restriction that an array type might be completed by
8145 // the initializer; note that later code assumes this restriction.
8146 QualType BaseDeclType = VDecl->getType();
8147 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8148 BaseDeclType = Array->getElementType();
8149 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8150 diag::err_typecheck_decl_incomplete_type)) {
8151 RealDecl->setInvalidDecl();
8152 return;
8153 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008154
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008155 // The variable can not have an abstract class type.
8156 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8157 diag::err_abstract_type_in_decl,
8158 AbstractVariableType))
8159 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00008160 }
8161
Sebastian Redl31310a22010-02-01 20:16:42 +00008162 const VarDecl *Def;
8163 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00008164 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00008165 << VDecl->getDeclName();
8166 Diag(Def->getLocation(), diag::note_previous_definition);
8167 VDecl->setInvalidDecl();
8168 return;
8169 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008170
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008171 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00008172 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00008173 // C++ [class.static.data]p4
8174 // If a static data member is of const integral or const
8175 // enumeration type, its declaration in the class definition can
8176 // specify a constant-initializer which shall be an integral
8177 // constant expression (5.19). In that case, the member can appear
8178 // in integral constant expressions. The member shall still be
8179 // defined in a namespace scope if it is used in the program and the
8180 // namespace scope definition shall not contain an initializer.
8181 //
8182 // We already performed a redefinition check above, but for static
8183 // data members we also need to check whether there was an in-class
8184 // declaration with an initializer.
8185 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00008186 Diag(VDecl->getLocation(), diag::err_redefinition)
8187 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00008188 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8189 return;
8190 }
Douglas Gregor275a3692009-03-10 23:43:53 +00008191
Douglas Gregora31040f2010-12-16 01:31:22 +00008192 if (VDecl->hasLocalStorage())
8193 getCurFunction()->setHasBranchProtectedScope();
8194
8195 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8196 VDecl->setInvalidDecl();
8197 return;
8198 }
8199 }
John McCalle46f62c2010-08-01 01:24:59 +00008200
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008201 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8202 // a kernel function cannot be initialized."
8203 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8204 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8205 VDecl->setInvalidDecl();
8206 return;
8207 }
8208
Steve Naroffbb204692007-09-12 14:07:44 +00008209 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00008210 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00008211 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008212
Douglas Gregor1344e942013-03-07 22:57:58 +00008213 // Expressions default to 'id' when we're in a debugger
8214 // and we are assigning it to a variable of Objective-C pointer type.
8215 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8216 Init->getType() == Context.UnknownAnyTy) {
8217 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8218 if (Result.isInvalid()) {
8219 VDecl->setInvalidDecl();
8220 return;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008221 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008222 Init = Result.take();
8223 }
Richard Smith01888722011-12-15 19:20:59 +00008224
8225 // Perform the initialization.
8226 if (!VDecl->isInvalidDecl()) {
8227 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8228 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00008229 = DirectInit ?
8230 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8231 Init->getLocStart(),
8232 Init->getLocEnd())
8233 : InitializationKind::CreateDirectList(
8234 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00008235 : InitializationKind::CreateCopy(VDecl->getLocation(),
8236 Init->getLocStart());
8237
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008238 MultiExprArg Args = Init;
8239 if (CXXDirectInit)
8240 Args = MultiExprArg(CXXDirectInit->getExprs(),
8241 CXXDirectInit->getNumExprs());
8242
8243 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8244 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith01888722011-12-15 19:20:59 +00008245 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00008246 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00008247 return;
Steve Naroffbb204692007-09-12 14:07:44 +00008248 }
Richard Smith01888722011-12-15 19:20:59 +00008249
8250 Init = Result.takeAs<Expr>();
8251 }
8252
Richard Trieu568f7852012-10-01 17:39:51 +00008253 // Check for self-references within variable initializers.
8254 // Variables declared within a function/method body (except for references)
8255 // are handled by a dataflow analysis.
8256 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8257 VDecl->getType()->isReferenceType()) {
8258 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8259 }
8260
Richard Smith01888722011-12-15 19:20:59 +00008261 // If the type changed, it means we had an incomplete type that was
8262 // completed by the initializer. For example:
8263 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00008264 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00008265 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00008266 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00008267
Jordan Rosee10f4d32012-09-15 02:48:31 +00008268 if (!VDecl->isInvalidDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00008269 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8270
Jordan Rosee10f4d32012-09-15 02:48:31 +00008271 if (VDecl->hasAttr<BlocksAttr>())
8272 checkRetainCycles(VDecl, Init);
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008273
8274 // It is safe to assign a weak reference into a strong variable.
8275 // Although this code can still have problems:
8276 // id x = self.weakProp;
8277 // id y = self.weakProp;
8278 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8279 // paths through the function. This should be revisited if
8280 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek904a3262012-12-20 22:31:27 +00008281 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008282 DiagnosticsEngine::Level Level =
8283 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8284 Init->getLocStart());
8285 if (Level != DiagnosticsEngine::Ignored)
8286 getCurFunction()->markSafeWeakUse(Init);
8287 }
Jordan Rosee10f4d32012-09-15 02:48:31 +00008288 }
8289
Richard Smith41956372013-01-14 22:39:08 +00008290 // The initialization is usually a full-expression.
8291 //
8292 // FIXME: If this is a braced initialization of an aggregate, it is not
8293 // an expression, and each individual field initializer is a separate
8294 // full-expression. For instance, in:
8295 //
8296 // struct Temp { ~Temp(); };
8297 // struct S { S(Temp); };
8298 // struct T { S a, b; } t = { Temp(), Temp() }
8299 //
8300 // we should destroy the first Temp before constructing the second.
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008301 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8302 false,
8303 VDecl->isConstexpr());
Richard Smith41956372013-01-14 22:39:08 +00008304 if (Result.isInvalid()) {
8305 VDecl->setInvalidDecl();
8306 return;
8307 }
8308 Init = Result.take();
8309
Richard Smith01888722011-12-15 19:20:59 +00008310 // Attach the initializer to the decl.
8311 VDecl->setInit(Init);
8312
8313 if (VDecl->isLocalVarDecl()) {
8314 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8315 // static storage duration shall be constant expressions or string literals.
8316 // C++ does not have this restriction.
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008317 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8318 if (VDecl->getStorageClass() == SC_Static)
8319 CheckForConstantInitializer(Init, DclT);
8320 // C89 is stricter than C99 for non-static aggregate types.
8321 // C89 6.5.7p3: All the expressions [...] in an initializer list
8322 // for an object that has aggregate or union type shall be
8323 // constant expressions.
8324 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanella82026302013-07-22 19:10:20 +00008325 isa<InitListExpr>(Init) &&
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008326 !Init->isConstantInitializer(Context, false))
8327 Diag(Init->getExprLoc(),
8328 diag::ext_aggregate_init_not_constant)
8329 << Init->getSourceRange();
8330 }
Mike Stump1eb44332009-09-09 15:08:12 +00008331 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00008332 VDecl->getLexicalDeclContext()->isRecord()) {
8333 // This is an in-class initialization for a static data member, e.g.,
8334 //
8335 // struct S {
8336 // static const int value = 17;
8337 // };
8338
Douglas Gregor021c3b32009-03-11 23:00:04 +00008339 // C++ [class.mem]p4:
8340 // A member-declarator can contain a constant-initializer only
8341 // if it declares a static member (9.4) of const integral or
8342 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00008343 //
Richard Smith01888722011-12-15 19:20:59 +00008344 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00008345 // If a non-volatile const static data member is of integral or
8346 // enumeration type, its declaration in the class definition can
8347 // specify a brace-or-equal-initializer in which every initalizer-clause
8348 // that is an assignment-expression is a constant expression. A static
8349 // data member of literal type can be declared in the class definition
8350 // with the constexpr specifier; if so, its declaration shall specify a
8351 // brace-or-equal-initializer in which every initializer-clause that is
8352 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00008353
8354 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00008355 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00008356
Richard Smithc6d990a2011-09-29 19:11:37 +00008357 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00008358 // type. We separately check that every constexpr variable is of literal
8359 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00008360 } else if (VDecl->isConstexpr()) {
8361
John McCall4e635642010-09-10 23:21:22 +00008362 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00008363 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00008364 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8365 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008366 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008367
8368 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00008369 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00008370 // Check whether the expression is a constant expression.
8371 SourceLocation Loc;
Richard Smith80ad52f2013-01-02 11:42:31 +00008372 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00008373 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00008374 // in-class initializer cannot be volatile.
8375 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8376 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00008377 ; // Nothing to check.
8378 else if (Init->isIntegerConstantExpr(Context, &Loc))
8379 ; // Ok, it's an ICE!
8380 else if (Init->isEvaluatable(Context)) {
8381 // If we can constant fold the initializer through heroics, accept it,
8382 // but report this as a use of an extension for -pedantic.
8383 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8384 << Init->getSourceRange();
8385 } else {
8386 // Otherwise, this is some crazy unknown case. Report the issue at the
8387 // location provided by the isIntegerConstantExpr failed check.
8388 Diag(Loc, diag::err_in_class_initializer_non_constant)
8389 << Init->getSourceRange();
8390 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008391 }
8392
Richard Smith01888722011-12-15 19:20:59 +00008393 // We allow foldable floating-point constants as an extension.
8394 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithb4b1d692013-01-25 04:22:16 +00008395 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8396 // it anyway and provide a fixit to add the 'constexpr'.
8397 if (getLangOpts().CPlusPlus11) {
David Blaikiea367e9d2013-01-29 22:26:08 +00008398 Diag(VDecl->getLocation(),
8399 diag::ext_in_class_initializer_float_type_cxx11)
8400 << DclT << Init->getSourceRange();
8401 Diag(VDecl->getLocStart(),
8402 diag::note_in_class_initializer_float_type_cxx11)
8403 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithb4b1d692013-01-25 04:22:16 +00008404 } else {
8405 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8406 << DclT << Init->getSourceRange();
John McCall4e635642010-09-10 23:21:22 +00008407
Richard Smithb4b1d692013-01-25 04:22:16 +00008408 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8409 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8410 << Init->getSourceRange();
8411 VDecl->setInvalidDecl();
8412 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00008413 }
Richard Smith947be192011-09-29 23:18:34 +00008414
Richard Smith01888722011-12-15 19:20:59 +00008415 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smitha10b9782013-04-22 15:31:51 +00008416 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith947be192011-09-29 23:18:34 +00008417 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00008418 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00008419 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8420 VDecl->setConstexpr(true);
8421
Richard Smithc6d990a2011-09-29 19:11:37 +00008422 } else {
8423 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00008424 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00008425 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008426 }
Steve Naroff248a7532008-04-15 22:42:06 +00008427 } else if (VDecl->isFileVarDecl()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008428 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008429 (!getLangOpts().CPlusPlus ||
Rafael Espindola5b34b9c2013-03-29 07:56:05 +00008430 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smithd0629eb2013-09-27 20:14:12 +00008431 VDecl->isExternC())) &&
8432 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff410e3e22007-09-12 20:13:48 +00008433 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00008434
Richard Smith01888722011-12-15 19:20:59 +00008435 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00008436 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00008437 CheckForConstantInitializer(Init, DclT);
Richard Smith6a570f62013-04-14 20:11:31 +00008438 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8439 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8440 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smithb6b127f2013-04-15 08:07:34 +00008441 !Init->isConstantInitializer(
8442 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6a570f62013-04-14 20:11:31 +00008443 // GNU C++98 edits for __thread, [basic.start.init]p4:
8444 // An object of thread storage duration shall not require dynamic
8445 // initialization.
8446 // FIXME: Need strict checking here.
8447 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8448 if (getLangOpts().CPlusPlus11)
8449 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8450 }
Steve Naroffbb204692007-09-12 14:07:44 +00008451 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008452
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008453 // We will represent direct-initialization similarly to copy-initialization:
8454 // int x(1); -as-> int x = 1;
8455 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8456 //
8457 // Clients that want to distinguish between the two forms, can check for
8458 // direct initializer using VarDecl::getInitStyle().
8459 // A major benefit is that clients that don't particularly care about which
8460 // exactly form was it (like the CodeGen) can handle both cases without
8461 // special case code.
8462
8463 // C++ 8.5p11:
8464 // The form of initialization (using parentheses or '=') is generally
8465 // insignificant, but does matter when the entity being initialized has a
8466 // class type.
8467 if (CXXDirectInit) {
8468 assert(DirectInit && "Call-style initializer must be direct init.");
8469 VDecl->setInitStyle(VarDecl::CallInit);
8470 } else if (DirectInit) {
8471 // This must be list-initialization. No other way is direct-initialization.
8472 VDecl->setInitStyle(VarDecl::ListInit);
8473 }
8474
John McCall2998d6b2011-01-19 11:48:09 +00008475 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00008476}
8477
John McCall7727acf2010-03-31 02:13:20 +00008478/// ActOnInitializerError - Given that there was an error parsing an
8479/// initializer for the given declaration, try to return to some form
8480/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00008481void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00008482 // Our main concern here is re-establishing invariants like "a
8483 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00008484 if (!D || D->isInvalidDecl()) return;
8485
8486 VarDecl *VD = dyn_cast<VarDecl>(D);
8487 if (!VD) return;
8488
Richard Smith34b41d92011-02-20 03:19:35 +00008489 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00008490 if (ParsingInitForAutoVars.count(D)) {
8491 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008492 return;
8493 }
8494
John McCall7727acf2010-03-31 02:13:20 +00008495 QualType Ty = VD->getType();
8496 if (Ty->isDependentType()) return;
8497
8498 // Require a complete type.
8499 if (RequireCompleteType(VD->getLocation(),
8500 Context.getBaseElementType(Ty),
8501 diag::err_typecheck_decl_incomplete_type)) {
8502 VD->setInvalidDecl();
8503 return;
8504 }
8505
8506 // Require an abstract type.
8507 if (RequireNonAbstractType(VD->getLocation(), Ty,
8508 diag::err_abstract_type_in_decl,
8509 AbstractVariableType)) {
8510 VD->setInvalidDecl();
8511 return;
8512 }
8513
8514 // Don't bother complaining about constructors or destructors,
8515 // though.
8516}
8517
John McCalld226f652010-08-21 09:40:31 +00008518void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00008519 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00008520 // If there is no declaration, there was an error parsing it. Just ignore it.
8521 if (RealDecl == 0)
8522 return;
8523
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008524 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8525 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008526
Richard Smithdd4b3502011-12-25 21:17:58 +00008527 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00008528 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00008529 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8530 << Var->getDeclName() << Type;
8531 Var->setInvalidDecl();
8532 return;
8533 }
Mike Stump1eb44332009-09-09 15:08:12 +00008534
Richard Smithdd4b3502011-12-25 21:17:58 +00008535 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00008536 // the constexpr specifier; if so, its declaration shall specify
8537 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00008538 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8539 // the definition of a variable [...] or the declaration of a static data
8540 // member.
8541 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8542 if (Var->isStaticDataMember())
8543 Diag(Var->getLocation(),
8544 diag::err_constexpr_static_mem_var_requires_init)
8545 << Var->getDeclName();
8546 else
8547 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00008548 Var->setInvalidDecl();
8549 return;
8550 }
8551
Douglas Gregor60c93c92010-02-09 07:26:29 +00008552 switch (Var->isThisDeclarationADefinition()) {
8553 case VarDecl::Definition:
8554 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8555 break;
8556
8557 // We have an out-of-line definition of a static data member
8558 // that has an in-class initializer, so we type-check this like
8559 // a declaration.
8560 //
8561 // Fall through
8562
8563 case VarDecl::DeclarationOnly:
8564 // It's only a declaration.
8565
8566 // Block scope. C99 6.7p7: If an identifier for an object is
8567 // declared with no linkage (C99 6.2.2p6), the type for the
8568 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00008569 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008570 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00008571 RequireCompleteType(Var->getLocation(), Type,
8572 diag::err_typecheck_decl_incomplete_type))
8573 Var->setInvalidDecl();
8574
8575 // Make sure that the type is not abstract.
8576 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8577 RequireNonAbstractType(Var->getLocation(), Type,
8578 diag::err_abstract_type_in_decl,
8579 AbstractVariableType))
8580 Var->setInvalidDecl();
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008581 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008582 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008583 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008584 Diag(Var->getLocation(), diag::note_private_extern);
8585 }
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008586
Douglas Gregor60c93c92010-02-09 07:26:29 +00008587 return;
8588
8589 case VarDecl::TentativeDefinition:
8590 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8591 // object that has file scope without an initializer, and without a
8592 // storage-class specifier or with the storage-class specifier "static",
8593 // constitutes a tentative definition. Note: A tentative definition with
8594 // external linkage is valid (C99 6.2.2p5).
8595 if (!Var->isInvalidDecl()) {
8596 if (const IncompleteArrayType *ArrayT
8597 = Context.getAsIncompleteArrayType(Type)) {
8598 if (RequireCompleteType(Var->getLocation(),
8599 ArrayT->getElementType(),
8600 diag::err_illegal_decl_array_incomplete_type))
8601 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00008602 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00008603 // C99 6.9.2p3: If the declaration of an identifier for an object is
8604 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8605 // declared type shall not be an incomplete type.
8606 // NOTE: code such as the following
8607 // static struct s;
8608 // struct s { int a; };
8609 // is accepted by gcc. Hence here we issue a warning instead of
8610 // an error and we do not invalidate the static declaration.
8611 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00008612 if (Var->isFirstDecl())
Douglas Gregor60c93c92010-02-09 07:26:29 +00008613 RequireCompleteType(Var->getLocation(), Type,
8614 diag::ext_typecheck_decl_incomplete_type);
8615 }
8616 }
8617
8618 // Record the tentative definition; we're done.
8619 if (!Var->isInvalidDecl())
8620 TentativeDefinitions.push_back(Var);
8621 return;
8622 }
8623
8624 // Provide a specific diagnostic for uninitialized variable
8625 // definitions with incomplete array type.
8626 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00008627 Diag(Var->getLocation(),
8628 diag::err_typecheck_incomplete_array_needs_initializer);
8629 Var->setInvalidDecl();
8630 return;
8631 }
8632
John McCallb567a8b2010-08-01 01:25:24 +00008633 // Provide a specific diagnostic for uninitialized variable
8634 // definitions with reference type.
8635 if (Type->isReferenceType()) {
8636 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8637 << Var->getDeclName()
8638 << SourceRange(Var->getLocation(), Var->getLocation());
8639 Var->setInvalidDecl();
8640 return;
8641 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008642
8643 // Do not attempt to type-check the default initializer for a
8644 // variable with dependent type.
8645 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00008646 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00008647
Douglas Gregor60c93c92010-02-09 07:26:29 +00008648 if (Var->isInvalidDecl())
8649 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00008650
Douglas Gregor60c93c92010-02-09 07:26:29 +00008651 if (RequireCompleteType(Var->getLocation(),
8652 Context.getBaseElementType(Type),
8653 diag::err_typecheck_decl_incomplete_type)) {
8654 Var->setInvalidDecl();
8655 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008656 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008657
Douglas Gregor60c93c92010-02-09 07:26:29 +00008658 // The variable can not have an abstract class type.
8659 if (RequireNonAbstractType(Var->getLocation(), Type,
8660 diag::err_abstract_type_in_decl,
8661 AbstractVariableType)) {
8662 Var->setInvalidDecl();
8663 return;
8664 }
8665
Douglas Gregor4337dc72011-05-21 17:52:48 +00008666 // Check for jumps past the implicit initializer. C++0x
8667 // clarifies that this applies to a "variable with automatic
8668 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00008669 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00008670 // A program that jumps from a point where a variable with automatic
8671 // storage duration is not in scope to a point where it is in scope is
8672 // ill-formed unless the variable has scalar type, class type with a
8673 // trivial default constructor and a trivial destructor, a cv-qualified
8674 // version of one of these types, or an array of one of the preceding
8675 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00008676 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008677 if (const RecordType *Record
8678 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00008679 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00008680 // Mark the function for further checking even if the looser rules of
8681 // C++11 do not require such checks, so that we can diagnose
8682 // incompatibilities with C++98.
8683 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00008684 getCurFunction()->setHasBranchProtectedScope();
8685 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008686 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00008687
8688 // C++03 [dcl.init]p9:
8689 // If no initializer is specified for an object, and the
8690 // object is of (possibly cv-qualified) non-POD class type (or
8691 // array thereof), the object shall be default-initialized; if
8692 // the object is of const-qualified type, the underlying class
8693 // type shall have a user-declared default
8694 // constructor. Otherwise, if no initializer is specified for
8695 // a non- static object, the object and its subobjects, if
8696 // any, have an indeterminate initial value); if the object
8697 // or any of its subobjects are of const-qualified type, the
8698 // program is ill-formed.
8699 // C++0x [dcl.init]p11:
8700 // If no initializer is specified for an object, the object is
8701 // default-initialized; [...].
8702 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8703 InitializationKind Kind
8704 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00008705
8706 InitializationSequence InitSeq(*this, Entity, Kind, None);
8707 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor4337dc72011-05-21 17:52:48 +00008708 if (Init.isInvalid())
8709 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008710 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008711 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008712 // This is important for template substitution.
8713 Var->setInitStyle(VarDecl::CallInit);
8714 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00008715
John McCall2998d6b2011-01-19 11:48:09 +00008716 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008717 }
8718}
8719
Richard Smithad762fc2011-04-14 22:09:26 +00008720void Sema::ActOnCXXForRangeDecl(Decl *D) {
8721 VarDecl *VD = dyn_cast<VarDecl>(D);
8722 if (!VD) {
8723 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8724 D->setInvalidDecl();
8725 return;
8726 }
8727
8728 VD->setCXXForRangeDecl(true);
8729
8730 // for-range-declaration cannot be given a storage class specifier.
8731 int Error = -1;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008732 switch (VD->getStorageClass()) {
Richard Smithad762fc2011-04-14 22:09:26 +00008733 case SC_None:
8734 break;
8735 case SC_Extern:
8736 Error = 0;
8737 break;
8738 case SC_Static:
8739 Error = 1;
8740 break;
8741 case SC_PrivateExtern:
8742 Error = 2;
8743 break;
8744 case SC_Auto:
8745 Error = 3;
8746 break;
8747 case SC_Register:
8748 Error = 4;
8749 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008750 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00008751 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00008752 }
Richard Smithc6d990a2011-09-29 19:11:37 +00008753 if (VD->isConstexpr())
8754 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00008755 if (Error != -1) {
8756 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8757 << VD->getDeclName() << Error;
8758 D->setInvalidDecl();
8759 }
8760}
8761
John McCall2998d6b2011-01-19 11:48:09 +00008762void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8763 if (var->isInvalidDecl()) return;
8764
John McCallf85e1932011-06-15 23:02:42 +00008765 // In ARC, don't allow jumps past the implicit initialization of a
8766 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00008767 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00008768 var->hasLocalStorage()) {
8769 switch (var->getType().getObjCLifetime()) {
8770 case Qualifiers::OCL_None:
8771 case Qualifiers::OCL_ExplicitNone:
8772 case Qualifiers::OCL_Autoreleasing:
8773 break;
8774
8775 case Qualifiers::OCL_Weak:
8776 case Qualifiers::OCL_Strong:
8777 getCurFunction()->setHasBranchProtectedScope();
8778 break;
8779 }
8780 }
8781
Eli Friedmane4851f22012-10-23 20:19:32 +00008782 if (var->isThisDeclarationADefinition() &&
Eli Friedman2ae28e52013-09-24 23:10:08 +00008783 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimekacaf1102012-12-12 13:26:54 +00008784 getDiagnostics().getDiagnosticLevel(
8785 diag::warn_missing_variable_declarations,
8786 var->getLocation())) {
Eli Friedmane4851f22012-10-23 20:19:32 +00008787 // Find a previous declaration that's not a definition.
8788 VarDecl *prev = var->getPreviousDecl();
8789 while (prev && prev->isThisDeclarationADefinition())
8790 prev = prev->getPreviousDecl();
8791
8792 if (!prev)
8793 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8794 }
8795
Richard Smith6a570f62013-04-14 20:11:31 +00008796 if (var->getTLSKind() == VarDecl::TLS_Static &&
8797 var->getType().isDestructedType()) {
8798 // GNU C++98 edits for __thread, [basic.start.term]p3:
8799 // The type of an object with thread storage duration shall not
8800 // have a non-trivial destructor.
8801 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8802 if (getLangOpts().CPlusPlus11)
8803 Diag(var->getLocation(), diag::note_use_thread_local);
8804 }
8805
John McCall2998d6b2011-01-19 11:48:09 +00008806 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00008807 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00008808
Richard Smitha67d5032012-11-09 23:03:14 +00008809 QualType type = var->getType();
8810 if (type->isDependentType()) return;
John McCall2998d6b2011-01-19 11:48:09 +00008811
8812 // __block variables might require us to capture a copy-initializer.
8813 if (var->hasAttr<BlocksAttr>()) {
8814 // It's currently invalid to ever have a __block variable with an
8815 // array type; should we diagnose that here?
8816
8817 // Regardless, we don't want to ignore array nesting when
8818 // constructing this copy.
John McCall2998d6b2011-01-19 11:48:09 +00008819 if (type->isStructureOrClassType()) {
John McCallb760f112013-03-22 02:10:40 +00008820 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall2998d6b2011-01-19 11:48:09 +00008821 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00008822 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregor6cda3e62013-03-07 22:38:24 +00008823 ExprResult result
8824 = PerformMoveOrCopyInitialization(
8825 InitializedEntity::InitializeBlock(poi, type, false),
8826 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall2998d6b2011-01-19 11:48:09 +00008827 if (!result.isInvalid()) {
8828 result = MaybeCreateExprWithCleanups(result);
8829 Expr *init = result.takeAs<Expr>();
8830 Context.setBlockVarCopyInits(var, init);
8831 }
8832 }
8833 }
8834
Richard Smith66f85712011-11-07 22:16:17 +00008835 Expr *Init = var->getInit();
8836 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smitha67d5032012-11-09 23:03:14 +00008837 QualType baseType = Context.getBaseElementType(type);
Richard Smith66f85712011-11-07 22:16:17 +00008838
Richard Smith9568f0c2012-10-29 18:26:47 +00008839 if (!var->getDeclContext()->isDependentContext() &&
8840 Init && !Init->isValueDependent()) {
Richard Smith099e7f62011-12-19 06:19:21 +00008841 if (IsGlobal && !var->isConstexpr() &&
8842 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8843 var->getLocation())
Eli Friedman21cde052013-07-16 22:40:53 +00008844 != DiagnosticsEngine::Ignored) {
8845 // Warn about globals which don't have a constant initializer. Don't
8846 // warn about globals with a non-trivial destructor because we already
8847 // warned about them.
8848 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8849 if (!(RD && !RD->hasTrivialDestructor()) &&
8850 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8851 Diag(var->getLocation(), diag::warn_global_constructor)
8852 << Init->getSourceRange();
8853 }
Richard Smith099e7f62011-12-19 06:19:21 +00008854
Richard Smith099e7f62011-12-19 06:19:21 +00008855 if (var->isConstexpr()) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008856 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00008857 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8858 SourceLocation DiagLoc = var->getLocation();
8859 // If the note doesn't add any useful information other than a source
8860 // location, fold it into the primary diagnostic.
8861 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8862 diag::note_invalid_subexpr_in_const_expr) {
8863 DiagLoc = Notes[0].first;
8864 Notes.clear();
8865 }
8866 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8867 << var << Init->getSourceRange();
8868 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8869 Diag(Notes[I].first, Notes[I].second);
8870 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00008871 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00008872 // Check whether the initializer of a const variable of integral or
8873 // enumeration type is an ICE now, since we can't tell whether it was
8874 // initialized by a constant expression if we check later.
8875 var->checkInitIsICE();
8876 }
Richard Smith66f85712011-11-07 22:16:17 +00008877 }
John McCall2998d6b2011-01-19 11:48:09 +00008878
8879 // Require the destructor.
8880 if (const RecordType *recordType = baseType->getAs<RecordType>())
8881 FinalizeVarWithDestructor(var, recordType);
8882}
8883
Richard Smith483b9f32011-02-21 20:05:19 +00008884/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8885/// any semantic actions necessary after any initializer has been attached.
8886void
8887Sema::FinalizeDeclaration(Decl *ThisDecl) {
8888 // Note that we are no longer parsing the initializer for this declaration.
8889 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008890
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008891 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindolada844b32013-01-03 04:05:19 +00008892 if (!VD)
8893 return;
8894
Rafael Espindola29535ba2013-08-16 23:18:50 +00008895 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8896 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8897 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8898 VD->dropAttr<UsedAttr>();
8899 }
8900 }
8901
Rafael Espindolab1c0e202013-10-22 21:39:03 +00008902 if (!VD->isInvalidDecl() &&
8903 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8904 if (const VarDecl *Def = VD->getDefinition()) {
8905 if (Def->hasAttr<AliasAttr>()) {
8906 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8907 << VD->getDeclName();
8908 Diag(Def->getLocation(), diag::note_previous_definition);
8909 VD->setInvalidDecl();
8910 }
8911 }
8912 }
8913
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008914 const DeclContext *DC = VD->getDeclContext();
8915 // If there's a #pragma GCC visibility in scope, and this isn't a class
8916 // member, set the visibility of this variable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008917 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008918 AddPushedVisibilityAttribute(VD);
8919
Rafael Espindola6769ccb2013-01-03 04:29:20 +00008920 if (VD->isFileVarDecl())
8921 MarkUnusedFileScopedDecl(VD);
8922
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008923 // Now we have parsed the initializer and can update the table of magic
8924 // tag values.
Rafael Espindolada844b32013-01-03 04:05:19 +00008925 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8926 !VD->getType()->isIntegralOrEnumerationType())
8927 return;
8928
8929 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8930 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8931 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8932 I != E; ++I) {
8933 const Expr *MagicValueExpr = VD->getInit();
8934 if (!MagicValueExpr) {
8935 continue;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008936 }
Rafael Espindolada844b32013-01-03 04:05:19 +00008937 llvm::APSInt MagicValueInt;
8938 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8939 Diag(I->getRange().getBegin(),
8940 diag::err_type_tag_for_datatype_not_ice)
8941 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8942 continue;
8943 }
8944 if (MagicValueInt.getActiveBits() > 64) {
8945 Diag(I->getRange().getBegin(),
8946 diag::err_type_tag_for_datatype_too_large)
8947 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8948 continue;
8949 }
8950 uint64_t MagicValue = MagicValueInt.getZExtValue();
8951 RegisterTypeTagForDatatype(I->getArgumentKind(),
8952 MagicValue,
8953 I->getMatchingCType(),
8954 I->getLayoutCompatible(),
8955 I->getMustBeNull());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008956 }
Richard Smith483b9f32011-02-21 20:05:19 +00008957}
8958
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008959Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8960 ArrayRef<Decl *> Group) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00008961 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008962
8963 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00008964 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008965
David Majnemeraa824612013-09-17 23:57:10 +00008966 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008967 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemeraa824612013-09-17 23:57:10 +00008968 if (Decl *D = Group[i]) {
8969 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8970 if (!FirstDeclaratorInGroup)
8971 FirstDeclaratorInGroup = DD;
Richard Smith406c38e2011-02-23 00:37:57 +00008972 Decls.push_back(D);
David Majnemeraa824612013-09-17 23:57:10 +00008973 }
Richard Smith406c38e2011-02-23 00:37:57 +00008974
Eli Friedman5e867c82013-07-10 00:30:46 +00008975 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemeraa824612013-09-17 23:57:10 +00008976 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman5e867c82013-07-10 00:30:46 +00008977 HandleTagNumbering(*this, Tag);
David Majnemeraa824612013-09-17 23:57:10 +00008978 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8979 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8980 }
Eli Friedman5e867c82013-07-10 00:30:46 +00008981 }
David Blaikie66cff722012-11-14 01:52:05 +00008982
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008983 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith406c38e2011-02-23 00:37:57 +00008984}
8985
8986/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8987/// group, performing any necessary semantic checking.
8988Sema::DeclGroupPtrTy
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008989Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith406c38e2011-02-23 00:37:57 +00008990 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00008991 // C++0x [dcl.spec.auto]p7:
8992 // If the type deduced for the template parameter U is not the same in each
8993 // deduction, the program is ill-formed.
8994 // FIXME: When initializer-list support is added, a distinction is needed
8995 // between the deduced type U and the deduced type which 'auto' stands for.
8996 // auto a = 0, b = { 1, 2, 3 };
8997 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008998 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00008999 QualType Deduced;
9000 CanQualType DeducedCanon;
9001 VarDecl *DeducedDecl = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009002 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith34b41d92011-02-20 03:19:35 +00009003 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9004 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00009005 // Don't reissue diagnostics when instantiating a template.
9006 if (AT && D->isInvalidDecl())
9007 break;
Richard Smithdc7a4f52013-04-30 13:56:41 +00009008 QualType U = AT ? AT->getDeducedType() : QualType();
9009 if (!U.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00009010 CanQualType UCanon = Context.getCanonicalType(U);
9011 if (Deduced.isNull()) {
9012 Deduced = U;
9013 DeducedCanon = UCanon;
9014 DeducedDecl = D;
9015 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00009016 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9017 diag::err_auto_different_deductions)
Richard Smithffd015e2013-05-04 04:19:27 +00009018 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith34b41d92011-02-20 03:19:35 +00009019 << Deduced << DeducedDecl->getDeclName()
9020 << U << D->getDeclName()
9021 << DeducedDecl->getInit()->getSourceRange()
9022 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00009023 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00009024 break;
9025 }
9026 }
9027 }
9028 }
9029 }
9030
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009031 ActOnDocumentableDecls(Group);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009032
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009033 return DeclGroupPtrTy::make(
9034 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00009035}
Steve Naroffe1223f72007-08-28 03:03:08 +00009036
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009037void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009038 ActOnDocumentableDecls(D);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009039}
9040
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009041void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009042 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009043 if (Group.empty() || !Group[0])
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009044 return;
9045
9046 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9047 Group[0]->getLocation())
9048 == DiagnosticsEngine::Ignored)
9049 return;
9050
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009051 if (Group.size() >= 2) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009052 // This is a decl group. Normally it will contain only declarations
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009053 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009054 // additional declaration references:
9055 // 'typedef struct S {} S;'
9056 // 'typedef struct S *S;'
9057 // 'struct S *pS;'
9058 // FinalizeDeclaratorGroup adds these as separate declarations.
9059 Decl *MaybeTagDecl = Group[0];
9060 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009061 Group = Group.slice(1);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009062 }
9063 }
9064
9065 // See if there are any new comments that are not attached to a decl.
9066 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9067 if (!Comments.empty() &&
9068 !Comments.back()->isAttached()) {
9069 // There is at least one comment that not attached to a decl.
9070 // Maybe it should be attached to one of these decls?
9071 //
9072 // Note that this way we pick up not only comments that precede the
9073 // declaration, but also comments that *follow* the declaration -- thanks to
9074 // the lookahead in the lexer: we've consumed the semicolon and looked
9075 // ahead through comments.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009076 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko19523542012-09-29 11:40:46 +00009077 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009078 }
9079}
Chris Lattner682bf922009-03-29 16:50:03 +00009080
Chris Lattner04421082008-04-08 04:40:51 +00009081/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9082/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00009083Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00009084 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00009085
Chris Lattner04421082008-04-08 04:40:51 +00009086 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Valifad9e132013-09-26 19:54:12 +00009087
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009088 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00009089 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009090 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00009091 StorageClass = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00009092 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009093 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9094 StorageClass = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009095 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00009096 Diag(DS.getStorageClassSpecLoc(),
9097 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00009098 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00009099 }
Eli Friedman63054b32009-04-19 20:27:55 +00009100
Richard Smithec642442013-04-12 22:46:28 +00009101 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9102 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9103 << DeclSpec::getSpecifierName(TSCS);
9104 if (DS.isConstexprSpecified())
9105 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smithaf1fc7a2011-08-15 21:04:07 +00009106 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00009107
Richard Smithec642442013-04-12 22:46:28 +00009108 DiagnoseFunctionSpecifiers(DS);
Eli Friedman85a53192009-04-07 19:37:57 +00009109
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00009110 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00009111 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009112
David Blaikie4e4d0842012-03-11 07:00:24 +00009113 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009114 // Check that there are no default arguments inside the type of this
9115 // parameter.
9116 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009117
9118 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9119 if (D.getCXXScopeSpec().isSet()) {
9120 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9121 << D.getCXXScopeSpec().getRange();
9122 D.getCXXScopeSpec().clear();
9123 }
Douglas Gregor402abb52009-05-28 23:31:59 +00009124 }
9125
Sean Hunt7533a5b2010-11-03 01:07:06 +00009126 // Ensure we have a valid name
9127 IdentifierInfo *II = 0;
9128 if (D.hasName()) {
9129 II = D.getIdentifier();
9130 if (!II) {
9131 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9132 << GetNameForDeclarator(D).getName().getAsString();
9133 D.setInvalidType(true);
9134 }
9135 }
9136
Chris Lattnerd84aac12010-02-22 00:40:25 +00009137 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00009138 if (II) {
John McCall10f28732010-03-18 06:42:38 +00009139 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9140 ForRedeclaration);
9141 LookupName(R, S);
9142 if (R.isSingleResult()) {
9143 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00009144 if (PrevDecl->isTemplateParameter()) {
9145 // Maybe we will complain about the shadowed template parameter.
9146 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9147 // Just pretend that we didn't see the previous declaration.
9148 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00009149 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00009150 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00009151 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00009152
Chris Lattnercf79b012009-01-21 02:38:50 +00009153 // Recover by removing the name
9154 II = 0;
9155 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009156 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00009157 }
Chris Lattner04421082008-04-08 04:40:51 +00009158 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009159 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00009160
John McCall7a9813c2010-01-22 00:28:27 +00009161 // Temporarily put parameter variables in the translation unit, not
9162 // the enclosing context. This prevents them from accidentally
9163 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009164 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00009165 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009166 D.getIdentifierLoc(), II,
9167 parmDeclType, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009168 StorageClass);
Mike Stump1eb44332009-09-09 15:08:12 +00009169
Chris Lattnereaaebc72009-04-25 08:06:05 +00009170 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00009171 New->setInvalidDecl();
9172
9173 assert(S->isFunctionPrototypeScope());
9174 assert(S->getFunctionPrototypeDepth() >= 1);
9175 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9176 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009177
Douglas Gregor44b43212008-12-11 16:49:14 +00009178 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00009179 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009180 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00009181 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00009182
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009183 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00009184
Douglas Gregore3895852011-09-12 18:37:38 +00009185 if (D.getDeclSpec().isModulePrivateSpecified())
9186 Diag(New->getLocation(), diag::err_module_private_local)
9187 << 1 << New->getDeclName()
9188 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9189 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9190
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009191 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00009192 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9193 }
John McCalld226f652010-08-21 09:40:31 +00009194 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00009195}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00009196
John McCall82dc0092010-06-04 11:21:44 +00009197/// \brief Synthesizes a variable for a parameter arising from a
9198/// typedef.
9199ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9200 SourceLocation Loc,
9201 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009202 /* FIXME: setting StartLoc == Loc.
9203 Would it be worth to modify callers so as to provide proper source
9204 location for the unnamed parameters, embedding the parameter's type? */
9205 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00009206 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009207 SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00009208 Param->setImplicit();
9209 return Param;
9210}
9211
John McCallfbce0e12010-08-24 09:05:15 +00009212void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9213 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00009214 // Don't diagnose unused-parameter errors in template instantiations; we
9215 // will already have done so in the template itself.
9216 if (!ActiveTemplateInstantiations.empty())
9217 return;
9218
9219 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00009220 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00009221 !(*Param)->hasAttr<UnusedAttr>()) {
9222 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9223 << (*Param)->getDeclName();
9224 }
9225 }
9226}
9227
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009228void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9229 ParmVarDecl * const *ParamEnd,
9230 QualType ReturnTy,
9231 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009232 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009233 return;
9234
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009235 // Warn if the return value is pass-by-value and larger than the specified
9236 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00009237 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009238 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009239 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009240 Diag(D->getLocation(), diag::warn_return_value_size)
9241 << D->getDeclName() << Size;
9242 }
9243
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009244 // Warn if any parameter is pass-by-value and larger than the specified
9245 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009246 for (; Param != ParamEnd; ++Param) {
9247 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00009248 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009249 continue;
9250 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009251 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009252 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9253 << (*Param)->getDeclName() << Size;
9254 }
9255}
9256
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009257ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9258 SourceLocation NameLoc, IdentifierInfo *Name,
9259 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009260 VarDecl::StorageClass StorageClass) {
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009261 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00009262 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009263 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009264 T->isObjCLifetimeType()) {
9265
9266 Qualifiers::ObjCLifetime lifetime;
9267
9268 // Special cases for arrays:
9269 // - if it's const, use __unsafe_unretained
9270 // - otherwise, it's an error
9271 if (T->isArrayType()) {
9272 if (!T.isConstQualified()) {
9273 DelayedDiagnostics.add(
9274 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanian175fb102011-10-03 22:11:57 +00009275 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009276 }
9277 lifetime = Qualifiers::OCL_ExplicitNone;
9278 } else {
9279 lifetime = T->getObjCARCImplicitLifetime();
9280 }
9281 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCallf85e1932011-06-15 23:02:42 +00009282 }
9283
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009284 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00009285 Context.getAdjustedParameterType(T),
9286 TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009287 StorageClass, 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009288
9289 // Parameters can not be abstract class types.
9290 // For record types, this is done by the AbstractClassUsageDiagnoser once
9291 // the class has been completely parsed.
9292 if (!CurContext->isRecord() &&
9293 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9294 AbstractParamType))
9295 New->setInvalidDecl();
9296
9297 // Parameter declarators cannot be interface types. All ObjC objects are
9298 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00009299 if (T->isObjCObjectType()) {
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009300 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009301 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009302 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009303 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009304 T = Context.getObjCObjectPointerType(T);
9305 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009306 }
9307
9308 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9309 // duration shall not be qualified by an address-space qualifier."
9310 // Since all parameters have automatic store duration, they can not have
9311 // an address space.
9312 if (T.getAddressSpace() != 0) {
9313 Diag(NameLoc, diag::err_arg_with_address_space);
9314 New->setInvalidDecl();
9315 }
9316
9317 return New;
9318}
9319
Douglas Gregora3a83512009-04-01 23:51:29 +00009320void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9321 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009322 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00009323
Reid Spencer5f016e22007-07-11 17:01:13 +00009324 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9325 // for a K&R function.
9326 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00009327 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9328 --i;
Chris Lattner04421082008-04-08 04:40:51 +00009329 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009330 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009331 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009332 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009333 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00009334 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00009335 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00009336 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00009337
Reid Spencer5f016e22007-07-11 17:01:13 +00009338 // Implicitly declare the argument as type 'int' for lack of a better
9339 // type.
John McCall0b7e6782011-03-24 11:26:52 +00009340 AttributeFactory attrs;
9341 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00009342 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00009343 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00009344 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00009345 PrevSpec, DiagID);
Abramo Bagnara16467f22012-10-04 21:38:29 +00009346 // Use the identifier location for the type source range.
9347 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9348 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattner04421082008-04-08 04:40:51 +00009349 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9350 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00009351 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00009352 }
9353 }
Mike Stump1eb44332009-09-09 15:08:12 +00009354 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00009355}
9356
Richard Smith87162c22012-04-17 22:30:01 +00009357Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00009358 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009359 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00009360 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00009361
Douglas Gregor45fa5602011-11-07 20:56:01 +00009362 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009363 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner682bf922009-03-29 16:50:03 +00009364 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00009365}
9366
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009367static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9368 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009369 // Don't warn about invalid declarations.
9370 if (FD->isInvalidDecl())
9371 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009372
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009373 // Or declarations that aren't global.
9374 if (!FD->isGlobal())
9375 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009376
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009377 // Don't warn about C++ member functions.
9378 if (isa<CXXMethodDecl>(FD))
9379 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009380
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009381 // Don't warn about 'main'.
9382 if (FD->isMain())
9383 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009384
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009385 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00009386 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009387 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009388
9389 // Don't warn about function templates.
9390 if (FD->getDescribedFunctionTemplate())
9391 return false;
9392
9393 // Don't warn about function template specializations.
9394 if (FD->isFunctionTemplateSpecialization())
9395 return false;
9396
Tanya Lattnera95b4f72012-07-26 00:08:28 +00009397 // Don't warn for OpenCL kernels.
9398 if (FD->hasAttr<OpenCLKernelAttr>())
9399 return false;
Richard Smitha41c97a2013-09-20 01:15:31 +00009400
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009401 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00009402 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9403 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009404 // Ignore any declarations that occur in function or method
9405 // scope, because they aren't visible from the header.
Richard Smitha41c97a2013-09-20 01:15:31 +00009406 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009407 continue;
Richard Smitha41c97a2013-09-20 01:15:31 +00009408
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009409 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009410 if (FD->getNumParams() == 0)
9411 PossibleZeroParamPrototype = Prev;
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009412 break;
9413 }
Richard Smitha41c97a2013-09-20 01:15:31 +00009414
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009415 return MissingPrototype;
9416}
9417
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009418void
9419Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9420 const FunctionDecl *EffectiveDefinition) {
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009421 // Don't complain if we're in GNU89 mode and the previous definition
9422 // was an extern inline function.
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009423 const FunctionDecl *Definition = EffectiveDefinition;
9424 if (!Definition)
9425 if (!FD->isDefined(Definition))
9426 return;
9427
9428 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009429 return;
9430
9431 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9432 Definition->getStorageClass() == SC_Extern)
9433 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00009434 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009435 else
9436 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9437
9438 Diag(Definition->getLocation(), diag::note_previous_definition);
9439 FD->setInvalidDecl();
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009440}
Faisal Valic00e4192013-11-07 05:17:06 +00009441
9442
Faisal Valibef582b2013-10-23 16:10:50 +00009443static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9444 Sema &S) {
9445 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Valid78d6592013-11-12 01:40:44 +00009446
9447 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valibef582b2013-10-23 16:10:50 +00009448 LSI->CallOperator = CallOperator;
9449 LSI->Lambda = LambdaClass;
9450 LSI->ReturnType = CallOperator->getResultType();
9451 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9452
9453 if (LCD == LCD_None)
9454 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9455 else if (LCD == LCD_ByCopy)
9456 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9457 else if (LCD == LCD_ByRef)
9458 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9459 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9460
9461 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9462 LSI->Mutable = !CallOperator->isConst();
9463
Faisal Valic00e4192013-11-07 05:17:06 +00009464 // Add the captures to the LSI so they can be noted as already
9465 // captured within tryCaptureVar.
9466 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9467 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9468 if (C->capturesVariable()) {
9469 VarDecl *VD = C->getCapturedVar();
9470 if (VD->isInitCapture())
9471 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9472 QualType CaptureType = VD->getType();
9473 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9474 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9475 /*RefersToEnclosingLocal*/true, C->getLocation(),
9476 /*EllipsisLoc*/C->isPackExpansion()
9477 ? C->getEllipsisLoc() : SourceLocation(),
9478 CaptureType, /*Expr*/ 0);
9479
9480 } else if (C->capturesThis()) {
9481 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9482 S.getCurrentThisType(), /*Expr*/ 0);
9483 }
9484 }
Faisal Valibef582b2013-10-23 16:10:50 +00009485}
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009486
John McCalld226f652010-08-21 09:40:31 +00009487Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00009488 // Clear the last template instantiation error context.
9489 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9490
Douglas Gregor52591bf2009-06-24 00:54:41 +00009491 if (!D)
9492 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00009493 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00009494
John McCalld226f652010-08-21 09:40:31 +00009495 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00009496 FD = FunTmpl->getTemplatedDecl();
9497 else
John McCalld226f652010-08-21 09:40:31 +00009498 FD = cast<FunctionDecl>(D);
Faisal Valifad9e132013-09-26 19:54:12 +00009499 // If we are instantiating a generic lambda call operator, push
9500 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valibef582b2013-10-23 16:10:50 +00009501 // that's already been calculated (ActOnLambdaExpr) to prime the current
9502 // LambdaScopeInfo.
9503 // When the template operator is being specialized, the LambdaScopeInfo,
9504 // has to be properly restored so that tryCaptureVariable doesn't try
9505 // and capture any new variables. In addition when calculating potential
9506 // captures during transformation of nested lambdas, it is necessary to
9507 // have the LSI properly restored.
Faisal Vali998c5182013-09-29 20:15:45 +00009508 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Valifad9e132013-09-26 19:54:12 +00009509 assert(ActiveTemplateInstantiations.size() &&
9510 "There should be an active template instantiation on the stack "
9511 "when instantiating a generic lambda!");
Faisal Valibef582b2013-10-23 16:10:50 +00009512 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Valifad9e132013-09-26 19:54:12 +00009513 }
9514 else
9515 // Enter a new function scope
9516 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00009517
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009518 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009519 if (!FD->isLateTemplateParsed())
9520 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009521
Douglas Gregorcda9c672009-02-16 17:45:42 +00009522 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009523 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindolaad24ad42013-06-13 18:34:17 +00009524 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9525 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00009526 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00009527 FD->setInvalidDecl();
9528 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00009529 }
9530
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009531 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00009532 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9533 QualType ResultType = FD->getResultType();
9534 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00009535 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00009536 RequireCompleteType(FD->getLocation(), ResultType,
9537 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009538 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009539
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009540 // GNU warning -Wmissing-prototypes:
9541 // Warn if a global function is defined without a previous
9542 // prototype declaration. This warning is issued even if the
9543 // definition itself provides a prototype. The aim is to detect
9544 // global functions that fail to be declared in header files.
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009545 const FunctionDecl *PossibleZeroParamPrototype = 0;
9546 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009547 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithac83a3c2013-06-25 20:34:17 +00009548
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009549 if (PossibleZeroParamPrototype) {
Richard Smithac83a3c2013-06-25 20:34:17 +00009550 // We found a declaration that is not a prototype,
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009551 // but that could be a zero-parameter prototype
Richard Smithac83a3c2013-06-25 20:34:17 +00009552 if (TypeSourceInfo *TI =
9553 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9554 TypeLoc TL = TI->getTypeLoc();
9555 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9556 Diag(PossibleZeroParamPrototype->getLocation(),
9557 diag::note_declaration_not_a_prototype)
9558 << PossibleZeroParamPrototype
9559 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9560 }
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009561 }
9562 }
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009563
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009564 if (FnBodyScope)
9565 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009566
Chris Lattner04421082008-04-08 04:40:51 +00009567 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00009568 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9569 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00009570
9571 // Introduce our parameters into the function scope
9572 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9573 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00009574 Param->setOwningFunction(FD);
9575
Chris Lattner04421082008-04-08 04:40:51 +00009576 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009577 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009578 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00009579
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009580 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00009581 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009582 }
Chris Lattner04421082008-04-08 04:40:51 +00009583
James Molloy16f1f712012-02-29 10:24:19 +00009584 // If we had any tags defined in the function prototype,
9585 // introduce them into the function scope.
9586 if (FnBodyScope) {
Robert Wilhelm834c0582013-08-09 18:02:13 +00009587 for (ArrayRef<NamedDecl *>::iterator
9588 I = FD->getDeclsInPrototypeScope().begin(),
9589 E = FD->getDeclsInPrototypeScope().end();
9590 I != E; ++I) {
James Molloy16f1f712012-02-29 10:24:19 +00009591 NamedDecl *D = *I;
9592
9593 // Some of these decls (like enums) may have been pinned to the translation unit
9594 // for lack of a real context earlier. If so, remove from the translation unit
9595 // and reattach to the current context.
9596 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9597 // Is the decl actually in the context?
9598 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9599 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9600 if (*DI == D) {
9601 Context.getTranslationUnitDecl()->removeDecl(D);
9602 break;
9603 }
9604 }
9605 // Either way, reassign the lexical decl context to our FunctionDecl.
9606 D->setLexicalDeclContext(CurContext);
9607 }
9608
9609 // If the decl has a non-null name, make accessible in the current scope.
9610 if (!D->getName().empty())
9611 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9612
9613 // Similarly, dive into enums and fish their constants out, making them
9614 // accessible in this scope.
9615 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9616 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9617 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie581deb32012-06-06 20:45:41 +00009618 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy16f1f712012-02-29 10:24:19 +00009619 }
9620 }
9621 }
9622
Richard Smith87162c22012-04-17 22:30:01 +00009623 // Ensure that the function's exception specification is instantiated.
9624 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9625 ResolveExceptionSpec(D->getLocation(), FPT);
9626
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009627 // Checking attributes of current function definition
9628 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00009629 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9630 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9631 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00009632 // Microsoft accepts dllimport for functions defined within class scope.
9633 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00009634 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009635 Diag(FD->getLocation(),
9636 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9637 << "dllimport";
9638 FD->setInvalidDecl();
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009639 return D;
Ted Kremenek12911a82010-02-21 05:12:53 +00009640 }
9641
9642 // Visual C++ appears to not think this is an issue, so only issue
9643 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009644 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009645 // If a symbol previously declared dllimport is later defined, the
9646 // attribute is ignored in subsequent references, and a warning is
9647 // emitted.
9648 Diag(FD->getLocation(),
9649 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00009650 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009651 }
9652 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +00009653 // We want to attach documentation to original Decl (which might be
9654 // a function template).
9655 ActOnDocumentableDecl(D);
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009656 return D;
Reid Spencer5f016e22007-07-11 17:01:13 +00009657}
9658
Douglas Gregor5077c382010-05-15 06:01:05 +00009659/// \brief Given the set of return statements within a function body,
9660/// compute the variables that are subject to the named return value
9661/// optimization.
9662///
9663/// Each of the variables that is subject to the named return value
9664/// optimization will be marked as NRVO variables in the AST, and any
9665/// return statement that has a marked NRVO variable as its NRVO candidate can
9666/// use the named return value optimization.
9667///
9668/// This function applies a very simplistic algorithm for NRVO: if every return
9669/// statement in the function has the same NRVO candidate, that candidate is
9670/// the NRVO variable.
9671///
9672/// FIXME: Employ a smarter algorithm that accounts for multiple return
9673/// statements and the lifetimes of the NRVO candidates. We should be able to
9674/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009675void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00009676 ReturnStmt **Returns = Scope->Returns.data();
9677
Douglas Gregor5077c382010-05-15 06:01:05 +00009678 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00009679 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00009680 if (!Returns[I]->getNRVOCandidate())
9681 return;
9682
9683 if (!NRVOCandidate)
9684 NRVOCandidate = Returns[I]->getNRVOCandidate();
9685 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9686 return;
9687 }
9688
9689 if (NRVOCandidate)
9690 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9691}
9692
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009693bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smithd1bac8d2012-11-27 21:31:01 +00009694 if (!Consumer.shouldSkipFunctionBody(D))
9695 return false;
9696
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009697 if (isa<ObjCMethodDecl>(D))
9698 return true;
9699
9700 FunctionDecl *FD = 0;
9701 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9702 FD = FTD->getTemplatedDecl();
9703 else
9704 FD = cast<FunctionDecl>(D);
9705
9706 // We cannot skip the body of a function (or function template) which is
9707 // constexpr, since we may need to evaluate its body in order to parse the
9708 // rest of the file.
Richard Smith25d8c852013-05-10 04:31:10 +00009709 // We cannot skip the body of a function with an undeduced return type,
9710 // because any callers of that function need to know the type.
9711 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009712}
9713
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009714Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009715 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009716 FD->setHasSkippedBody();
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009717 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009718 MD->setHasSkippedBody();
9719 return ActOnFinishFunctionBody(Decl, 0);
9720}
9721
John McCallf312b1e2010-08-26 23:41:50 +00009722Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009723 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009724}
9725
John McCall9ae2f072010-08-23 23:25:46 +00009726Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9727 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00009728 FunctionDecl *FD = 0;
9729 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9730 if (FunTmpl)
9731 FD = FunTmpl->getTemplatedDecl();
9732 else
9733 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9734
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009735 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009736 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009737
Douglas Gregord83d0402009-08-22 00:34:47 +00009738 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00009739 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00009740
Richard Smith25d8c852013-05-10 04:31:10 +00009741 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9742 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9743 // If the function has a deduced result type but contains no 'return'
9744 // statements, the result type as written must be exactly 'auto', and
9745 // the deduced result type is 'void'.
9746 if (!FD->getResultType()->getAs<AutoType>()) {
9747 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9748 << FD->getResultType();
9749 FD->setInvalidDecl();
9750 } else {
9751 // Substitute 'void' for the 'auto' in the type.
9752 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9753 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9754 Context.adjustDeducedFunctionResultType(
9755 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith60e141e2013-05-04 07:00:32 +00009756 }
9757 }
9758
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009759 // The only way to be included in UndefinedButUsed is if there is an
9760 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewycky995e26b2013-01-31 03:23:57 +00009761 // is the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00009762 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00009763 if (!FD->isExternallyVisible())
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009764 UndefinedButUsed.erase(FD);
9765 else if (FD->isInlined() &&
9766 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9767 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9768 UndefinedButUsed.erase(FD);
9769 }
Nick Lewycky995e26b2013-01-31 03:23:57 +00009770
John McCall75d8ba32012-02-14 19:50:52 +00009771 // If the function implicitly returns zero (like 'main') or is naked,
9772 // don't complain about missing return statements.
9773 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009774 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00009775
Francois Pichet6a247472011-05-11 02:14:46 +00009776 // MSVC permits the use of pure specifier (=0) on function definition,
9777 // defined at class scope, warn about this non standard construct.
Reid Kleckner5dbed662013-10-08 22:45:29 +00009778 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet6a247472011-05-11 02:14:46 +00009779 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9780
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009781 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009782 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009783 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9784 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009785
9786 // If this is a constructor, we need a vtable.
9787 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9788 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00009789
Jordan Rose7dd900e2012-07-02 21:19:23 +00009790 // Try to apply the named return value optimization. We have to check
9791 // if we can do this here because lambdas keep return statements around
9792 // to deduce an implicit return type.
9793 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9794 !FD->isDependentContext())
9795 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009796 }
9797
Douglas Gregor76e3da52012-02-08 20:17:14 +00009798 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9799 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00009800 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00009801 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00009802 MD->setBody(Body);
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009803 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009804 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009805 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9806 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00009807
9808 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009809 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009810 }
Jordan Rose535a5d02012-10-19 16:05:26 +00009811 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanian9f559832012-09-10 16:51:09 +00009812 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9813 << MD->getSelector().getAsString();
Jordan Rose535a5d02012-10-19 16:05:26 +00009814 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00009815 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00009816 } else {
John McCalld226f652010-08-21 09:40:31 +00009817 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00009818 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009819
Jordan Rose535a5d02012-10-19 16:05:26 +00009820 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman95aac152012-08-01 21:02:59 +00009821 "This should only be set for ObjC methods, which should have been "
9822 "handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00009823
Reid Spencer5f016e22007-07-11 17:01:13 +00009824 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009825 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009826 // C++ constructors that have function-try-blocks can't have return
9827 // statements in the handlers of that block. (C++ [except.handle]p14)
9828 // Verify this.
9829 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9830 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9831
Richard Smith37bee672011-08-12 18:44:32 +00009832 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00009833 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00009834 !dcl->isInvalidDecl() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009835 !hasAnyUnrecoverableErrorsInThisFunction() &&
9836 !PP.isCodeCompletionEnabled())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009837 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00009838
John McCall15442822010-08-04 01:04:25 +00009839 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9840 if (!Destructor->getParent()->isDependentType())
9841 CheckDestructor(Destructor);
9842
John McCallef027fe2010-03-16 21:39:52 +00009843 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9844 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00009845 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009846
9847 // If any errors have occurred, clear out any temporaries that may have
9848 // been leftover. This ensures that these temporaries won't be picked up for
9849 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00009850 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00009851 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00009852 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00009853 }
9854 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9855 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009856 // Since the body is valid, issue any analysis-based warnings that are
9857 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009858 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009859 }
9860
Richard Smith86c3ae42012-02-13 03:54:03 +00009861 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9862 (!CheckConstexprFunctionDecl(FD) ||
9863 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00009864 FD->setInvalidDecl();
9865
John McCall80ee6e82011-11-10 05:35:25 +00009866 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00009867 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00009868 assert(MaybeODRUseExprs.empty() &&
9869 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009870 }
9871
John McCall90f97892010-03-25 22:08:03 +00009872 if (!IsInstantiation)
9873 PopDeclContext();
9874
Eli Friedmanec9ea722012-01-05 03:35:19 +00009875 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregord5b57282009-11-15 07:07:58 +00009876 // If any errors have occurred, clear out any temporaries that may have
9877 // been leftover. This ensures that these temporaries won't be picked up for
9878 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00009879 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00009880 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00009881 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00009882
John McCalld226f652010-08-21 09:40:31 +00009883 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00009884}
9885
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009886
9887/// When we finish delayed parsing of an attribute, we must attach it to the
9888/// relevant Decl.
9889void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9890 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00009891 // Always attach attributes to the underlying decl.
9892 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9893 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00009894 ProcessDeclAttributeList(S, D, Attrs.getList());
9895
9896 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9897 if (Method->isStatic())
9898 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009899}
9900
9901
Reid Spencer5f016e22007-07-11 17:01:13 +00009902/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9903/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00009904NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00009905 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00009906 // Before we produce a declaration for an implicitly defined
9907 // function, see whether there was a locally-scoped declaration of
9908 // this name as a function or variable. If so, use that
9909 // (non-visible) declaration, and complain about it.
Richard Smith662f41b2013-06-18 20:15:12 +00009910 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9911 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9912 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9913 return ExternCPrev;
Douglas Gregor63935192009-03-02 00:19:53 +00009914 }
9915
Chris Lattner37d10842008-05-05 21:18:06 +00009916 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009917 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009918 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00009919 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00009920 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009921 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00009922 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009923 diag_id = diag::warn_implicit_function_decl;
9924 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00009925
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009926 // Because typo correction is expensive, only do it if the implicit
9927 // function declaration is going to be treated as an error.
9928 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9929 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00009930 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009931 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smith2d670972013-08-17 00:46:16 +00009932 LookupOrdinaryName, S, 0, Validator)))
9933 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9934 /*ErrorRecovery*/false);
Hans Wennborg122de3e2011-12-06 09:46:12 +00009935 }
9936
Reid Spencer5f016e22007-07-11 17:01:13 +00009937 // Set a Declarator for the implicit definition: int foo();
9938 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00009939 AttributeFactory attrFactory;
9940 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00009941 unsigned DiagID;
9942 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00009943 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00009944 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009945 SourceLocation NoLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009946 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009947 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9948 /*IsAmbiguous=*/false,
9949 /*RParenLoc=*/NoLoc,
9950 /*ArgInfo=*/0,
9951 /*NumArgs=*/0,
9952 /*EllipsisLoc=*/NoLoc,
9953 /*RParenLoc=*/NoLoc,
9954 /*TypeQuals=*/0,
9955 /*RefQualifierIsLvalueRef=*/true,
9956 /*RefQualifierLoc=*/NoLoc,
9957 /*ConstQualifierLoc=*/NoLoc,
9958 /*VolatileQualifierLoc=*/NoLoc,
9959 /*MutableLoc=*/NoLoc,
9960 EST_None,
9961 /*ESpecLoc=*/NoLoc,
9962 /*Exceptions=*/0,
9963 /*ExceptionRanges=*/0,
9964 /*NumExceptions=*/0,
9965 /*NoexceptExpr=*/0,
9966 Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00009967 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00009968 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00009969 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00009970
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009971 // Insert this function into translation-unit scope.
9972
9973 DeclContext *PrevDC = CurContext;
9974 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009975
Jordan Rose41f3f3a2013-03-05 01:27:54 +00009976 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00009977 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009978
9979 CurContext = PrevDC;
9980
Douglas Gregor3c385e52009-02-14 18:57:46 +00009981 AddKnownFunctionAttributes(FD);
9982
Steve Naroffe2ef8152008-04-04 14:32:09 +00009983 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009984}
9985
Douglas Gregor3c385e52009-02-14 18:57:46 +00009986/// \brief Adds any function attributes that we know a priori based on
9987/// the declaration of this function.
9988///
9989/// These attributes can apply both to implicitly-declared builtins
9990/// (like __builtin___printf_chk) or to library-declared functions
9991/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009992///
9993/// We need to check for duplicate attributes both here and where user-written
9994/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +00009995void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9996 if (FD->isInvalidDecl())
9997 return;
9998
9999 // If this is a built-in function, map its builtin attributes to
10000 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +000010001 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +000010002 // Handle printf-formatting attributes.
10003 unsigned FormatIdx;
10004 bool HasVAListArg;
10005 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010006 if (!FD->getAttr<FormatAttr>()) {
10007 const char *fmt = "printf";
10008 unsigned int NumParams = FD->getNumParams();
10009 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10010 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10011 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +000010012 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010013 &Context.Idents.get(fmt),
10014 FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +000010015 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010016 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010017 }
Ted Kremenekbee05c12010-07-16 02:11:15 +000010018 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10019 HasVAListArg)) {
10020 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010021 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010022 &Context.Idents.get("scanf"),
10023 FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +000010024 HasVAListArg ? 0 : FormatIdx+2));
10025 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010026
10027 // Mark const if we don't care about errno and that is the only
10028 // thing preventing the function from being const. This allows
10029 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +000010030 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010031 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010032 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010033 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010034 }
Mike Stump0feecbb2009-07-27 19:14:18 +000010035
Rafael Espindola67004152011-10-12 19:51:18 +000010036 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10037 !FD->getAttr<ReturnsTwiceAttr>())
10038 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010039 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010040 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010041 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010042 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +000010043 }
10044
10045 IdentifierInfo *Name = FD->getIdentifier();
10046 if (!Name)
10047 return;
David Blaikie4e4d0842012-03-11 07:00:24 +000010048 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +000010049 FD->getDeclContext()->isTranslationUnit()) ||
10050 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +000010051 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +000010052 LinkageSpecDecl::lang_c)) {
10053 // Okay: this could be a libc/libm/Objective-C function we know
10054 // about.
10055 } else
10056 return;
10057
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010058 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +000010059 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +000010060 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010061 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010062 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010063 &Context.Idents.get("printf"), 2,
Eli Friedmand7dad722009-06-10 04:01:38 +000010064 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +000010065 }
Jordan Rose8a64f882012-08-08 21:17:31 +000010066
10067 if (Name->isStr("__CFStringMakeConstantString")) {
10068 // We already have a __builtin___CFStringMakeConstantString,
10069 // but builds that use -fno-constant-cfstrings don't go through that.
10070 if (!FD->getAttr<FormatArgAttr>())
10071 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10072 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010073}
Reid Spencer5f016e22007-07-11 17:01:13 +000010074
Fariborz Jahanian0f3bb9e2013-11-19 00:09:48 +000010075static inline bool isTollFreeBridgeCFRefType(TypedefDecl *TD) {
10076 TypedefNameDecl * TDefNameDecl = TD;
10077 const Type *TP = TDefNameDecl->getUnderlyingType().getTypePtr();
10078 while (const TypedefType *TDef = dyn_cast<TypedefType>(TP)) {
10079 TDefNameDecl = TDef->getDecl();
10080 TP = TDefNameDecl->getUnderlyingType().getTypePtr();
10081 }
10082
10083 StringRef TDName = TDefNameDecl->getIdentifier()->getName();
10084 return (TDName.startswith("CF") && TDName.endswith("Ref"));
10085}
10086
10087/// CheckObjCBridgeAttribute - Checks that objc_bridge attribute is
10088/// properly applied to a typedef of a pointer to struct/union/class
10089static void CheckObjCBridgeAttribute(Sema &S, TypedefDecl *TD) {
10090 QualType T = TD->getUnderlyingType();
10091 if (!T->isPointerType())
10092 return;
10093 T = T->getPointeeType();
10094 if (T->isStructureType() || T->isUnionType() || T->isClassType())
10095 if (RecordDecl *RD = T->getAs<RecordType>()->getDecl())
10096 if (RD->hasAttr<ObjCBridgeAttr>() && !isTollFreeBridgeCFRefType(TD))
10097 S.Diag(TD->getLocStart(), diag::err_objc_bridge_not_cftype);
10098}
10099
John McCallba6a9bd2009-10-24 08:00:42 +000010100TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000010101 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010102 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +000010103 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +000010104
John McCalla93c9342009-12-07 02:54:59 +000010105 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +000010106 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +000010107 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +000010108 }
10109
Reid Spencer5f016e22007-07-11 17:01:13 +000010110 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +000010111 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010112 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +000010113 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +000010114 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +000010115 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +000010116
John McCallcde5a402011-02-01 08:20:08 +000010117 // Bail out immediately if we have an invalid declaration.
10118 if (D.isInvalidType()) {
10119 NewTD->setInvalidDecl();
10120 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +000010121 }
10122
Fariborz Jahanian0f3bb9e2013-11-19 00:09:48 +000010123 CheckObjCBridgeAttribute(*this, NewTD);
10124
Douglas Gregore3895852011-09-12 18:37:38 +000010125 if (D.getDeclSpec().isModulePrivateSpecified()) {
10126 if (CurContext->isFunctionOrMethod())
10127 Diag(NewTD->getLocation(), diag::err_module_private_local)
10128 << 2 << NewTD->getDeclName()
10129 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10130 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10131 else
10132 NewTD->setModulePrivate();
10133 }
Douglas Gregor8d267c52011-09-09 02:06:17 +000010134
John McCallcde5a402011-02-01 08:20:08 +000010135 // C++ [dcl.typedef]p8:
10136 // If the typedef declaration defines an unnamed class (or
10137 // enum), the first typedef-name declared by the declaration
10138 // to be that class type (or enum type) is used to denote the
10139 // class type (or enum type) for linkage purposes only.
10140 // We need to check whether the type was declared in the declaration.
10141 switch (D.getDeclSpec().getTypeSpecType()) {
10142 case TST_enum:
10143 case TST_struct:
Joao Matos6666ed42012-08-31 18:45:21 +000010144 case TST_interface:
John McCallcde5a402011-02-01 08:20:08 +000010145 case TST_union:
10146 case TST_class: {
10147 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10148
10149 // Do nothing if the tag is not anonymous or already has an
10150 // associated typedef (from an earlier typedef in this decl group).
10151 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +000010152 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +000010153
10154 // A well-formed anonymous tag must always be a TUK_Definition.
10155 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10156
10157 // The type must match the tag exactly; no qualifiers allowed.
10158 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10159 break;
10160
10161 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +000010162 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +000010163 break;
10164 }
10165
10166 default:
10167 break;
10168 }
10169
Steve Naroff5912a352007-08-28 20:14:24 +000010170 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +000010171}
10172
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010173
Richard Smithf1c66b42012-03-14 23:13:10 +000010174/// \brief Check that this is a valid underlying type for an enum declaration.
10175bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10176 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10177 QualType T = TI->getType();
10178
Eli Friedman2fcff832012-12-18 02:37:32 +000010179 if (T->isDependentType())
Richard Smithf1c66b42012-03-14 23:13:10 +000010180 return false;
10181
Eli Friedman2fcff832012-12-18 02:37:32 +000010182 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10183 if (BT->isInteger())
10184 return false;
10185
Richard Smithf1c66b42012-03-14 23:13:10 +000010186 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10187 return true;
10188}
10189
10190/// Check whether this is a valid redeclaration of a previous enumeration.
10191/// \return true if the redeclaration was invalid.
10192bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10193 QualType EnumUnderlyingTy,
10194 const EnumDecl *Prev) {
10195 bool IsFixed = !EnumUnderlyingTy.isNull();
10196
10197 if (IsScoped != Prev->isScoped()) {
10198 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10199 << Prev->isScoped();
10200 Diag(Prev->getLocation(), diag::note_previous_use);
10201 return true;
10202 }
10203
10204 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +000010205 if (!EnumUnderlyingTy->isDependentType() &&
10206 !Prev->getIntegerType()->isDependentType() &&
10207 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +000010208 Prev->getIntegerType())) {
10209 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10210 << EnumUnderlyingTy << Prev->getIntegerType();
10211 Diag(Prev->getLocation(), diag::note_previous_use);
10212 return true;
10213 }
10214 } else if (IsFixed != Prev->isFixed()) {
10215 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10216 << Prev->isFixed();
10217 Diag(Prev->getLocation(), diag::note_previous_use);
10218 return true;
10219 }
10220
10221 return false;
10222}
10223
Joao Matos6666ed42012-08-31 18:45:21 +000010224/// \brief Get diagnostic %select index for tag kind for
10225/// redeclaration diagnostic message.
10226/// WARNING: Indexes apply to particular diagnostics only!
10227///
10228/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +000010229static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +000010230 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +000010231 case TTK_Struct: return 0;
10232 case TTK_Interface: return 1;
10233 case TTK_Class: return 2;
10234 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +000010235 }
Joao Matos6666ed42012-08-31 18:45:21 +000010236}
10237
10238/// \brief Determine if tag kind is a class-key compatible with
10239/// class for redeclaration (class, struct, or __interface).
10240///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000010241/// \returns true iff the tag kind is compatible.
Joao Matos6666ed42012-08-31 18:45:21 +000010242static bool isClassCompatTagKind(TagTypeKind Tag)
10243{
10244 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10245}
10246
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010247/// \brief Determine whether a tag with a given kind is acceptable
10248/// as a redeclaration of the given tag declaration.
10249///
10250/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +000010251bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +000010252 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010253 SourceLocation NewTagLoc,
10254 const IdentifierInfo &Name) {
10255 // C++ [dcl.type.elab]p3:
10256 // The class-key or enum keyword present in the
10257 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010258 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010259 // refers. This rule also applies to the form of
10260 // elaborated-type-specifier that declares a class-name or
10261 // friend class since it can be construed as referring to the
10262 // definition of the class. Thus, in any
10263 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010264 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010265 // used to refer to a union (clause 9), and either the class or
10266 // struct class-key shall be used to refer to a class (clause 9)
10267 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010268 TagTypeKind OldTag = Previous->getTagKind();
Joao Matos6666ed42012-08-31 18:45:21 +000010269 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieubbf34c02011-06-10 03:11:26 +000010270 if (OldTag == NewTag)
10271 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010272
Joao Matos6666ed42012-08-31 18:45:21 +000010273 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010274 // Warn about the struct/class tag mismatch.
10275 bool isTemplate = false;
10276 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10277 isTemplate = Record->getDescribedClassTemplate();
10278
Richard Trieubbf34c02011-06-10 03:11:26 +000010279 if (!ActiveTemplateInstantiations.empty()) {
10280 // In a template instantiation, do not offer fix-its for tag mismatches
10281 // since they usually mess up the template instead of fixing the problem.
10282 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010283 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10284 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010285 return true;
10286 }
10287
10288 if (isDefinition) {
10289 // On definitions, check previous tags and issue a fix-it for each
10290 // one that doesn't match the current tag.
10291 if (Previous->getDefinition()) {
10292 // Don't suggest fix-its for redefinitions.
10293 return true;
10294 }
10295
10296 bool previousMismatch = false;
10297 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10298 E(Previous->redecls_end()); I != E; ++I) {
10299 if (I->getTagKind() != NewTag) {
10300 if (!previousMismatch) {
10301 previousMismatch = true;
10302 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010303 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10304 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieubbf34c02011-06-10 03:11:26 +000010305 }
10306 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010307 << getRedeclDiagFromTagKind(NewTag)
Richard Trieubbf34c02011-06-10 03:11:26 +000010308 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matos6666ed42012-08-31 18:45:21 +000010309 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieubbf34c02011-06-10 03:11:26 +000010310 }
10311 }
10312 return true;
10313 }
10314
10315 // Check for a previous definition. If current tag and definition
10316 // are same type, do nothing. If no definition, but disagree with
10317 // with previous tag type, give a warning, but no fix-it.
10318 const TagDecl *Redecl = Previous->getDefinition() ?
10319 Previous->getDefinition() : Previous;
10320 if (Redecl->getTagKind() == NewTag) {
10321 return true;
10322 }
10323
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010324 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010325 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10326 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010327 Diag(Redecl->getLocation(), diag::note_previous_use);
10328
10329 // If there is a previous defintion, suggest a fix-it.
10330 if (Previous->getDefinition()) {
10331 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010332 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieubbf34c02011-06-10 03:11:26 +000010333 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matos6666ed42012-08-31 18:45:21 +000010334 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieubbf34c02011-06-10 03:11:26 +000010335 }
10336
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010337 return true;
10338 }
10339 return false;
10340}
10341
Steve Naroff08d92e42007-09-15 18:49:24 +000010342/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +000010343/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +000010344/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +000010345/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +000010346Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +000010347 SourceLocation KWLoc, CXXScopeSpec &SS,
10348 IdentifierInfo *Name, SourceLocation NameLoc,
10349 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010350 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +000010351 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010352 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010353 SourceLocation ScopedEnumKWLoc,
10354 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010355 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010356 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +000010357 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +000010358 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000010359 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +000010360 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010361
Douglas Gregor402abb52009-05-28 23:31:59 +000010362 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010363 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +000010364 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +000010365
Douglas Gregor1fef4e62009-10-07 22:35:40 +000010366 // FIXME: Check explicit specializations more carefully.
10367 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010368 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +000010369
10370 // We only need to do this matching if we have template parameters
10371 // or a scope specifier, which also conveniently avoids this work
10372 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010373 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +000010374 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000010375 if (TemplateParameterList *TemplateParams =
10376 MatchTemplateParametersToScopeSpecifier(
10377 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10378 isExplicitSpecialization, Invalid)) {
Richard Smith725fe0e2013-04-01 21:43:41 +000010379 if (Kind == TTK_Enum) {
10380 Diag(KWLoc, diag::err_enum_template);
10381 return 0;
10382 }
10383
Douglas Gregord85bea22009-09-26 06:47:28 +000010384 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010385 // This is a declaration or definition of a class template (which may
10386 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010387
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010388 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +000010389 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010390
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010391 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +000010392 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010393 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010394 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010395 ModulePrivateLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010396 TemplateParameterLists.size()-1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010397 TemplateParameterLists.data());
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010398 return Result.get();
10399 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +000010400 // The "template<>" header is extraneous.
10401 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010402 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +000010403 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010404 }
Mike Stump1eb44332009-09-09 15:08:12 +000010405 }
10406 }
10407
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010408 // Figure out the underlying type if this a enum declaration. We need to do
10409 // this early, because it's needed to detect if this is an incompatible
10410 // redeclaration.
10411 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10412
10413 if (Kind == TTK_Enum) {
10414 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10415 // No underlying type explicitly specified, or we failed to parse the
10416 // type, default to int.
10417 EnumUnderlying = Context.IntTy.getTypePtr();
10418 else if (UnderlyingType.get()) {
10419 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10420 // integral type; any cv-qualification is ignored.
10421 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +000010422 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010423 EnumUnderlying = TI;
10424
Richard Smithf1c66b42012-03-14 23:13:10 +000010425 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010426 // Recover by falling back to int.
10427 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010428
Richard Smithf1c66b42012-03-14 23:13:10 +000010429 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010430 UPPC_FixedUnderlyingType))
10431 EnumUnderlying = Context.IntTy.getTypePtr();
10432
David Blaikie4e4d0842012-03-11 07:00:24 +000010433 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +000010434 // Microsoft enums are always of int type.
10435 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010436 }
10437
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010438 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010439 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010440 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010441
Chandler Carruth7bf36002010-03-01 21:17:36 +000010442 RedeclarationKind Redecl = ForRedeclaration;
10443 if (TUK == TUK_Friend || TUK == TUK_Reference)
10444 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +000010445
10446 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregord9433522013-06-27 20:42:30 +000010447 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010448 if (Name && SS.isNotEmpty()) {
10449 // We have a nested-name tag ('struct foo::bar').
10450
10451 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010452 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010453 Name = 0;
10454 goto CreateNewDecl;
10455 }
10456
John McCallc4e70192009-09-11 04:59:25 +000010457 // If this is a friend or a reference to a class in a dependent
10458 // context, don't try to make a decl for it.
10459 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10460 DC = computeDeclContext(SS, false);
10461 if (!DC) {
10462 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010463 return 0;
John McCallc4e70192009-09-11 04:59:25 +000010464 }
John McCall77bb1aa2010-05-01 00:40:08 +000010465 } else {
10466 DC = computeDeclContext(SS, true);
10467 if (!DC) {
10468 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10469 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +000010470 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +000010471 }
John McCallc4e70192009-09-11 04:59:25 +000010472 }
10473
John McCall77bb1aa2010-05-01 00:40:08 +000010474 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +000010475 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +000010476
Douglas Gregor1931b442009-02-03 00:34:39 +000010477 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010478 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +000010479 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +000010480
John McCall68263142009-11-18 22:49:29 +000010481 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010482 return 0;
John McCall6e247262009-10-10 05:48:19 +000010483
John McCall68263142009-11-18 22:49:29 +000010484 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010485 // Name lookup did not find anything. However, if the
10486 // nested-name-specifier refers to the current instantiation,
10487 // and that current instantiation has any dependent base
10488 // classes, we might find something at instantiation time: treat
10489 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +000010490 // But this only makes any sense for reference-like lookups.
10491 if (Previous.wasNotFoundInCurrentInstantiation() &&
10492 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010493 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010494 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010495 }
10496
10497 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +000010498 Diag(NameLoc, diag::err_not_tag_in_scope)
10499 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010500 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +000010501 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010502 goto CreateNewDecl;
10503 }
Chris Lattnercf79b012009-01-21 02:38:50 +000010504 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010505 // If this is a named struct, check to see if there was a previous forward
10506 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +000010507 // FIXME: We're looking into outer scopes here, even when we
10508 // shouldn't be. Doing so can result in ambiguities that we
10509 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +000010510 LookupName(Previous, S);
10511
John McCallc96cd7a2013-03-20 01:53:00 +000010512 // When declaring or defining a tag, ignore ambiguities introduced
10513 // by types using'ed into this scope.
Douglas Gregor93b6bce2011-05-09 21:46:33 +000010514 if (Previous.isAmbiguous() &&
10515 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +000010516 LookupResult::Filter F = Previous.makeFilter();
10517 while (F.hasNext()) {
10518 NamedDecl *ND = F.next();
10519 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10520 F.erase();
10521 }
10522 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +000010523 }
John McCallc96cd7a2013-03-20 01:53:00 +000010524
10525 // C++11 [namespace.memdef]p3:
10526 // If the name in a friend declaration is neither qualified nor
10527 // a template-id and the declaration is a function or an
10528 // elaborated-type-specifier, the lookup to determine whether
10529 // the entity has been previously declared shall not consider
10530 // any scopes outside the innermost enclosing namespace.
10531 //
10532 // Does it matter that this should be by scope instead of by
10533 // semantic context?
10534 if (!Previous.empty() && TUK == TUK_Friend) {
10535 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10536 LookupResult::Filter F = Previous.makeFilter();
10537 while (F.hasNext()) {
10538 NamedDecl *ND = F.next();
10539 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregord9433522013-06-27 20:42:30 +000010540 if (DC->isFileContext() &&
10541 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCallc96cd7a2013-03-20 01:53:00 +000010542 F.erase();
Douglas Gregord9433522013-06-27 20:42:30 +000010543 FriendSawTagOutsideEnclosingNamespace = true;
10544 }
John McCallc96cd7a2013-03-20 01:53:00 +000010545 }
10546 F.done();
10547 }
Douglas Gregor61c6c442011-05-04 00:25:33 +000010548
John McCall68263142009-11-18 22:49:29 +000010549 // Note: there used to be some attempt at recovery here.
10550 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010551 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +000010552
David Blaikie4e4d0842012-03-11 07:00:24 +000010553 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +000010554 // FIXME: This makes sure that we ignore the contexts associated
10555 // with C structs, unions, and enums when looking for a matching
10556 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +000010557 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010558 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10559 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +000010560 }
Douglas Gregor069ea642010-09-16 23:58:57 +000010561 } else if (S->isFunctionPrototypeScope()) {
10562 // If this is an enum declaration in function prototype scope, set its
10563 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +000010564 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +000010565 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010566 }
10567
John McCall68263142009-11-18 22:49:29 +000010568 if (Previous.isSingleResult() &&
10569 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010570 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +000010571 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +000010572 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +000010573 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +000010574 }
10575
David Blaikie4e4d0842012-03-11 07:00:24 +000010576 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010577 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010578 // This is a declaration of or a reference to "std::bad_alloc".
10579 isStdBadAlloc = true;
10580
John McCall68263142009-11-18 22:49:29 +000010581 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010582 // std::bad_alloc has been implicitly declared (but made invisible to
10583 // name lookup). Fill in this implicit declaration as the previous
10584 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010585 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010586 }
10587 }
John McCall68263142009-11-18 22:49:29 +000010588
John McCall9c86b512010-03-25 21:28:06 +000010589 // If we didn't find a previous declaration, and this is a reference
10590 // (or friend reference), move to the correct scope. In C++, we
10591 // also need to do a redeclaration lookup there, just in case
10592 // there's a shadow friend decl.
10593 if (Name && Previous.empty() &&
10594 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10595 if (Invalid) goto CreateNewDecl;
10596 assert(SS.isEmpty());
10597
10598 if (TUK == TUK_Reference) {
10599 // C++ [basic.scope.pdecl]p5:
10600 // -- for an elaborated-type-specifier of the form
10601 //
10602 // class-key identifier
10603 //
10604 // if the elaborated-type-specifier is used in the
10605 // decl-specifier-seq or parameter-declaration-clause of a
10606 // function defined in namespace scope, the identifier is
10607 // declared as a class-name in the namespace that contains
10608 // the declaration; otherwise, except as a friend
10609 // declaration, the identifier is declared in the smallest
10610 // non-class, non-function-prototype scope that contains the
10611 // declaration.
10612 //
10613 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10614 // C structs and unions.
10615 //
10616 // It is an error in C++ to declare (rather than define) an enum
10617 // type, including via an elaborated type specifier. We'll
10618 // diagnose that later; for now, declare the enum in the same
10619 // scope as we would have picked for any other tag type.
10620 //
10621 // GNU C also supports this behavior as part of its incomplete
10622 // enum types extension, while GNU C++ does not.
10623 //
10624 // Find the context where we'll be declaring the tag.
10625 // FIXME: We would like to maintain the current DeclContext as the
10626 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +000010627 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +000010628 SearchDC = SearchDC->getParent();
10629
10630 // Find the scope where we'll be declaring the tag.
10631 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010632 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +000010633 S->isFunctionPrototypeScope()) ||
10634 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +000010635 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCall9c86b512010-03-25 21:28:06 +000010636 S = S->getParent();
10637 } else {
10638 assert(TUK == TUK_Friend);
10639 // C++ [namespace.memdef]p3:
10640 // If a friend declaration in a non-local class first declares a
10641 // class or function, the friend class or function is a member of
10642 // the innermost enclosing namespace.
10643 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +000010644 }
10645
John McCall0d6b1642010-04-23 18:46:30 +000010646 // In C++, we need to do a redeclaration lookup to properly
10647 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +000010648 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +000010649 Previous.setRedeclarationKind(ForRedeclaration);
10650 LookupQualifiedName(Previous, SearchDC);
10651 }
10652 }
10653
John McCall68263142009-11-18 22:49:29 +000010654 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +000010655 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +000010656
10657 // It's okay to have a tag decl in the same scope as a typedef
10658 // which hides a tag decl in the same scope. Finding this
10659 // insanity with a redeclaration lookup can only actually happen
10660 // in C++.
10661 //
10662 // This is also okay for elaborated-type-specifiers, which is
10663 // technically forbidden by the current standard but which is
10664 // okay according to the likely resolution of an open issue;
10665 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +000010666 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +000010667 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +000010668 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10669 TagDecl *Tag = TT->getDecl();
10670 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010671 Tag->getDeclContext()->getRedeclContext()
10672 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +000010673 PrevDecl = Tag;
10674 Previous.clear();
10675 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +000010676 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +000010677 }
10678 }
10679 }
10680 }
10681
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010682 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010683 // If this is a use of a previous tag, or if the tag is already declared
10684 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010685 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +000010686 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +000010687 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010688 // Make sure that this wasn't declared as an enum and now used as a
10689 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +000010690 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10691 TUK == TUK_Definition, KWLoc,
10692 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +000010693 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010694 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10695 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +000010696 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +000010697 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +000010698 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +000010699 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10700 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +000010701 else
10702 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +000010703 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +000010704
Mike Stump1eb44332009-09-09 15:08:12 +000010705 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +000010706 Kind = PrevTagDecl->getTagKind();
10707 else {
10708 // Recover by making this an anonymous redefinition.
10709 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010710 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +000010711 Invalid = true;
10712 }
10713 }
10714
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010715 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10716 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10717
Richard Smithbdad7a22012-01-10 01:33:14 +000010718 // If this is an elaborated-type-specifier for a scoped enumeration,
10719 // the 'class' keyword is not necessary and not permitted.
10720 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10721 if (ScopedEnum)
10722 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10723 << PrevEnum->isScoped()
10724 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10725 return PrevTagDecl;
10726 }
10727
Richard Smithf1c66b42012-03-14 23:13:10 +000010728 QualType EnumUnderlyingTy;
10729 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10730 EnumUnderlyingTy = TI->getType();
10731 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10732 EnumUnderlyingTy = QualType(T, 0);
10733
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010734 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +000010735 // returning the previous declaration, unless this is a definition,
10736 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +000010737 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10738 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +000010739 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010740 }
10741
David Majnemer2ec2b842013-06-11 03:51:23 +000010742 // C++11 [class.mem]p1:
David Majnemer0f9b8552013-06-11 06:19:45 +000010743 // A member shall not be declared twice in the member-specification,
David Majnemer2ec2b842013-06-11 03:51:23 +000010744 // except that a nested class or member class template can be declared
10745 // and then later defined.
10746 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10747 S->isDeclScope(PrevDecl)) {
10748 Diag(NameLoc, diag::ext_member_redeclared);
10749 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10750 }
10751
Douglas Gregora3a83512009-04-01 23:51:29 +000010752 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010753 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +000010754
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010755 // FIXME: In the future, return a variant or some other clue
10756 // for the consumer of this Decl to know it doesn't own it.
10757 // For our current ASTs this shouldn't be a problem, but will
10758 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +000010759 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010760 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +000010761 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010762
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010763 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +000010764 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +000010765 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010766 // If we're defining a specialization and the previous definition
10767 // is from an implicit instantiation, don't emit an error
10768 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +000010769 bool IsExplicitSpecializationAfterInstantiation = false;
10770 if (isExplicitSpecialization) {
10771 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10772 IsExplicitSpecializationAfterInstantiation =
10773 RD->getTemplateSpecializationKind() !=
10774 TSK_ExplicitSpecialization;
10775 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10776 IsExplicitSpecializationAfterInstantiation =
10777 ED->getTemplateSpecializationKind() !=
10778 TSK_ExplicitSpecialization;
10779 }
10780
10781 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +000010782 // A redeclaration in function prototype scope in C isn't
10783 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +000010784 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +000010785 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10786 else
10787 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010788 Diag(Def->getLocation(), diag::note_previous_definition);
10789 // If this is a redefinition, recover by making this
10790 // struct be anonymous, which will make any later
10791 // references get the previous definition.
10792 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010793 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010794 Invalid = true;
10795 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010796 } else {
10797 // If the type is currently being defined, complain
10798 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +000010799 const TagType *Tag
10800 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010801 if (Tag->isBeingDefined()) {
10802 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +000010803 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010804 diag::note_previous_definition);
10805 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010806 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010807 Invalid = true;
10808 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010809 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010810
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010811 // Okay, this is definition of a previously declared or referenced
10812 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010813 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010814 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010815 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +000010816 // have a definition. Just create a new decl.
10817
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010818 } else {
10819 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +000010820 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010821 // new decl/type. We set PrevDecl to NULL so that the entities
10822 // have distinct types.
John McCall68263142009-11-18 22:49:29 +000010823 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010824 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010825 // If we get here, we're going to create a new Decl. If PrevDecl
10826 // is non-NULL, it's a definition of the tag declared by
10827 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +000010828
10829
10830 // Otherwise, PrevDecl is not a tag, but was found with tag
10831 // lookup. This is only actually possible in C++, where a few
10832 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010833 } else {
John McCall0d6b1642010-04-23 18:46:30 +000010834 // Use a better diagnostic if an elaborated-type-specifier
10835 // found the wrong kind of type on the first
10836 // (non-redeclaration) lookup.
10837 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10838 !Previous.isForRedeclaration()) {
10839 unsigned Kind = 0;
10840 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010841 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10842 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010843 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10844 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10845 Invalid = true;
10846
10847 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +000010848 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10849 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +000010850 // do nothing
10851
10852 // Diagnose implicit declarations introduced by elaborated types.
10853 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10854 unsigned Kind = 0;
10855 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010856 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10857 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010858 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10859 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10860 Invalid = true;
10861
10862 // Otherwise it's a declaration. Call out a particularly common
10863 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +000010864 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10865 unsigned Kind = 0;
10866 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +000010867 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +000010868 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +000010869 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10870 Invalid = true;
10871
10872 // Otherwise, diagnose.
10873 } else {
10874 // The tag name clashes with something else in the target scope,
10875 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +000010876 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010877 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010878 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010879 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010880 }
John McCall0d6b1642010-04-23 18:46:30 +000010881
10882 // The existing declaration isn't relevant to us; we're in a
10883 // new scope, so clear out the previous declaration.
10884 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010885 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010886 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000010887
Chris Lattnercc98eac2008-12-17 07:13:27 +000010888CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +000010889
John McCall68263142009-11-18 22:49:29 +000010890 TagDecl *PrevDecl = 0;
10891 if (Previous.isSingleResult())
10892 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10893
Reid Spencer5f016e22007-07-11 17:01:13 +000010894 // If there is an identifier, use the location of the identifier as the
10895 // location of the decl, otherwise use the location of the struct/union
10896 // keyword.
10897 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000010898
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010899 // Otherwise, create a new declaration. If there is a previous
10900 // declaration of the same entity, the two will be linked via
10901 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +000010902 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +000010903
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010904 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010905 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010906 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10907 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010908 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010909 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010910 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +000010911 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010912 if (TUK != TUK_Definition && !Invalid) {
10913 TagDecl *Def;
Douglas Gregorabde2c72013-03-25 22:22:35 +000010914 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10915 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010916 // C++0x: 7.2p2: opaque-enum-declaration.
10917 // Conflicts are diagnosed above. Do nothing.
10918 }
10919 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010920 Diag(Loc, diag::ext_forward_ref_enum_def)
10921 << New;
10922 Diag(Def->getLocation(), diag::note_previous_definition);
10923 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010924 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010925 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010926 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010927 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010928 DiagID = diag::err_forward_ref_enum;
10929 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010930
10931 // If this is a forward-declared reference to an enumeration, make a
10932 // note of it; we won't actually be introducing the declaration into
10933 // the declaration context.
10934 if (TUK == TUK_Reference)
10935 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010936 }
Douglas Gregor80711a22009-03-06 18:34:03 +000010937 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010938
10939 if (EnumUnderlying) {
10940 EnumDecl *ED = cast<EnumDecl>(New);
10941 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10942 ED->setIntegerTypeSourceInfo(TI);
10943 else
10944 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10945 ED->setPromotionType(ED->getIntegerType());
10946 }
10947
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000010948 } else {
10949 // struct/union/class
10950
Reid Spencer5f016e22007-07-11 17:01:13 +000010951 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10952 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +000010953 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +000010954 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010955 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010956 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010957
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010958 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010959 StdBadAlloc = cast<CXXRecordDecl>(New);
10960 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010961 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010962 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000010963 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010964
John McCallb6217662010-03-15 10:12:16 +000010965 // Maybe add qualifier info.
10966 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010967 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +000010968 // If this is either a declaration or a definition, check the
10969 // nested-name-specifier against the current context. We don't do this
10970 // for explicit specializations, because they have similar checking
10971 // (with more specific diagnostics) in the call to
10972 // CheckMemberSpecialization, below.
10973 if (!isExplicitSpecialization &&
10974 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10975 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10976 Invalid = true;
10977
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000010978 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010979 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +000010980 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010981 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010982 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +000010983 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010984 }
10985 else
10986 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +000010987 }
10988
Daniel Dunbar9f21f892010-05-27 01:53:40 +000010989 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10990 // Add alignment attributes if necessary; these attributes are checked when
10991 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010992 //
10993 // It is important for implementing the correct semantics that this
10994 // happen here (in act on tag decl). The #pragma pack stack is
10995 // maintained as a result of parser callbacks which can occur at
10996 // many points during the parsing of a struct declaration (because
10997 // the #pragma tokens are effectively skipped over during the
10998 // parsing of the struct).
Eli Friedman2016c8c2012-08-08 21:08:34 +000010999 if (TUK == TUK_Definition) {
11000 AddAlignmentAttributesForRecord(RD);
11001 AddMsStructLayoutForRecord(RD);
11002 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011003 }
11004
Douglas Gregor2ccd89c2011-12-20 18:11:52 +000011005 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +000011006 if (isExplicitSpecialization)
11007 Diag(New->getLocation(), diag::err_module_private_specialization)
11008 << 2
11009 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +000011010 // __module_private__ does not apply to local classes. However, we only
11011 // diagnose this as an error when the declaration specifiers are
11012 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +000011013 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +000011014 New->setModulePrivate();
11015 }
11016
Douglas Gregorf6b11852009-10-08 15:14:33 +000011017 // If this is a specialization of a member class (of a class template),
11018 // check the specialization.
John McCall68263142009-11-18 22:49:29 +000011019 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +000011020 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +000011021
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011022 if (Invalid)
11023 New->setInvalidDecl();
11024
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011025 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011026 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011027
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011028 // If we're declaring or defining a tag in function prototype scope
11029 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +000011030 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +000011031 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11032
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011033 // Set the lexical context. If the tag has a C++ scope specifier, the
11034 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +000011035 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011036
John McCall02cace72009-08-28 07:59:38 +000011037 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +000011038 // In Microsoft mode, a friend declaration also acts as a forward
11039 // declaration so we always pass true to setObjectOfFriendDecl to make
11040 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +000011041 if (TUK == TUK_Friend)
Richard Smith22050f22013-07-17 23:53:16 +000011042 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11043 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +000011044
Anders Carlsson0cf88302009-03-26 01:19:02 +000011045 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +000011046 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +000011047 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +000011048
John McCall0f434ec2009-07-31 02:45:11 +000011049 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011050 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +000011051
Reid Spencer5f016e22007-07-11 17:01:13 +000011052 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +000011053 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +000011054 // We might be replacing an existing declaration in the lookup tables;
11055 // if so, borrow its access specifier.
11056 if (PrevDecl)
11057 New->setAccess(PrevDecl->getAccess());
11058
Sebastian Redl7a126a42010-08-31 00:36:30 +000011059 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011060 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +000011061 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +000011062 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11063 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +000011064 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000011065 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011066 PushOnScopeChains(New, S, !IsForwardReference);
11067 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011068 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011069
Douglas Gregor4920f1f2009-01-12 22:49:06 +000011070 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011071 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +000011072 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000011073
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011074 // If this is the C FILE type, notify the AST context.
11075 if (IdentifierInfo *II = New->getIdentifier())
11076 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000011077 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011078 II->isStr("FILE"))
11079 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +000011080
James Molloy16f1f712012-02-29 10:24:19 +000011081 // If we were in function prototype scope (and not in C++ mode), add this
11082 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +000011083 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +000011084 InFunctionDeclarator && Name)
11085 DeclsInPrototypeScope.push_back(New);
11086
Rafael Espindola98ae8342012-05-10 02:50:16 +000011087 if (PrevDecl)
11088 mergeDeclAttributes(New, PrevDecl);
11089
Rafael Espindola71adc5b2012-07-17 15:14:47 +000011090 // If there's a #pragma GCC visibility in scope, set the visibility of this
11091 // record.
11092 AddPushedVisibilityAttribute(New);
11093
Douglas Gregor402abb52009-05-28 23:31:59 +000011094 OwnedDecl = true;
Richard Smith37ec8d52012-12-05 11:34:06 +000011095 // In C++, don't return an invalid declaration. We can't recover well from
11096 // the cases where we make the type anonymous.
11097 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Reid Spencer5f016e22007-07-11 17:01:13 +000011098}
11099
John McCalld226f652010-08-21 09:40:31 +000011100void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011101 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011102 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +000011103
Douglas Gregor72de6672009-01-08 20:45:30 +000011104 // Enter the tag context.
11105 PushDeclContext(S, Tag);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000011106
11107 ActOnDocumentableDecl(TagD);
Rafael Espindola5e065292012-07-12 04:47:34 +000011108
11109 // If there's a #pragma GCC visibility in scope, set the visibility of this
11110 // record.
11111 AddPushedVisibilityAttribute(Tag);
John McCallf9368152009-12-20 07:58:13 +000011112}
Douglas Gregor72de6672009-01-08 20:45:30 +000011113
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011114Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011115 assert(isa<ObjCContainerDecl>(IDecl) &&
11116 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11117 DeclContext *OCD = cast<DeclContext>(IDecl);
11118 assert(getContainingDC(OCD) == CurContext &&
11119 "The next DeclContext should be lexically contained in the current one.");
11120 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011121 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011122}
11123
John McCalld226f652010-08-21 09:40:31 +000011124void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011125 SourceLocation FinalLoc,
David Majnemer7121bdb2013-10-18 00:33:31 +000011126 bool IsFinalSpelledSealed,
John McCallf9368152009-12-20 07:58:13 +000011127 SourceLocation LBraceLoc) {
11128 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011129 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +000011130
John McCallf9368152009-12-20 07:58:13 +000011131 FieldCollector->StartClass();
11132
11133 if (!Record->getIdentifier())
11134 return;
11135
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011136 if (FinalLoc.isValid())
David Majnemer7121bdb2013-10-18 00:33:31 +000011137 Record->addAttr(new (Context)
11138 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11139
John McCallf9368152009-12-20 07:58:13 +000011140 // C++ [class]p2:
11141 // [...] The class-name is also inserted into the scope of the
11142 // class itself; this is known as the injected-class-name. For
11143 // purposes of access checking, the injected-class-name is treated
11144 // as if it were a public member name.
11145 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000011146 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11147 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +000011148 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +000011149 /*PrevDecl=*/0,
11150 /*DelayTypeCreation=*/true);
11151 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +000011152 InjectedClassName->setImplicit();
11153 InjectedClassName->setAccess(AS_public);
11154 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11155 InjectedClassName->setDescribedClassTemplate(Template);
11156 PushOnScopeChains(InjectedClassName, S);
11157 assert(InjectedClassName->isInjectedClassName() &&
11158 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +000011159}
11160
John McCalld226f652010-08-21 09:40:31 +000011161void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011162 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011163 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011164 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011165 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +000011166
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011167 // Make sure we "complete" the definition even it is invalid.
11168 if (Tag->isBeingDefined()) {
11169 assert(Tag->isInvalidDecl() && "We should already have completed it");
11170 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11171 RD->completeDefinition();
11172 }
11173
Douglas Gregor72de6672009-01-08 20:45:30 +000011174 if (isa<CXXRecordDecl>(Tag))
11175 FieldCollector->FinishClass();
11176
11177 // Exit this scope of this tag's definition.
11178 PopDeclContext();
Argyrios Kyrtzidis3d207e72013-01-29 18:00:54 +000011179
11180 if (getCurLexicalContext()->isObjCContainer() &&
11181 Tag->getDeclContext()->isFileContext())
11182 Tag->setTopLevelDeclInObjCContainer();
11183
Douglas Gregor72de6672009-01-08 20:45:30 +000011184 // Notify the consumer that we've defined a tag.
Serge Pavlov439b7012013-07-02 17:31:56 +000011185 if (!Tag->isInvalidDecl())
11186 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor72de6672009-01-08 20:45:30 +000011187}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +000011188
Fariborz Jahanian10af8792011-08-29 17:33:12 +000011189void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011190 // Exit this scope of this interface definition.
11191 PopDeclContext();
11192}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011193
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011194void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +000011195 assert(DC == CurContext && "Mismatch of container contexts");
11196 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011197 ActOnObjCContainerFinishDefinition();
11198}
11199
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011200void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11201 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011202 OriginalLexicalContext = 0;
11203}
11204
John McCalld226f652010-08-21 09:40:31 +000011205void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +000011206 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011207 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +000011208 Tag->setInvalidDecl();
11209
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011210 // Make sure we "complete" the definition even it is invalid.
11211 if (Tag->isBeingDefined()) {
11212 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11213 RD->completeDefinition();
11214 }
11215
John McCalla8cab012010-03-17 19:25:57 +000011216 // We're undoing ActOnTagStartDefinition here, not
11217 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11218 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +000011219
11220 PopDeclContext();
11221}
11222
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011223// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +000011224ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11225 IdentifierInfo *FieldName,
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011226 QualType FieldTy, bool IsMsStruct,
11227 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +000011228 // Default to true; that shouldn't confuse checks for emptiness
11229 if (ZeroWidth)
11230 *ZeroWidth = true;
11231
Chris Lattner24793662009-03-05 22:45:59 +000011232 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +000011233 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000011234 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +000011235 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +000011236 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +000011237 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011238 if (FieldName)
11239 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11240 << FieldName << FieldTy << BitWidth->getSourceRange();
11241 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11242 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +000011243 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11244 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +000011245 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011246
11247 // If the bit-width is type- or value-dependent, don't try to check
11248 // it now.
11249 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +000011250 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011251
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011252 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +000011253 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11254 if (ICE.isInvalid())
11255 return ICE;
11256 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011257
Eli Friedman1d954f62009-08-15 21:55:26 +000011258 if (Value != 0 && ZeroWidth)
11259 *ZeroWidth = false;
11260
Chris Lattnercd087072008-12-12 04:56:04 +000011261 // Zero-width bitfield is ok for anonymous field.
11262 if (Value == 0 && FieldName)
11263 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +000011264
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011265 if (Value.isSigned() && Value.isNegative()) {
11266 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +000011267 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011268 << FieldName << Value.toString(10);
11269 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11270 << Value.toString(10);
11271 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011272
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011273 if (!FieldTy->isDependentType()) {
11274 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011275 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011276 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlsson72468ec2010-04-16 15:16:32 +000011277 if (FieldName)
11278 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11279 << FieldName << (unsigned)Value.getZExtValue()
11280 << (unsigned)TypeSize;
11281
11282 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11283 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11284 }
11285
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011286 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +000011287 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11288 << FieldName << (unsigned)Value.getZExtValue()
11289 << (unsigned)TypeSize;
11290 else
11291 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11292 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011293 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011294 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011295
Richard Smith282e7e62012-02-04 09:53:13 +000011296 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011297}
11298
Richard Smith7a614d82011-06-11 17:19:42 +000011299/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +000011300/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +000011301Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011302 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +000011303 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +000011304 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smithca523302012-06-10 03:12:00 +000011305 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCalld226f652010-08-21 09:40:31 +000011306 return Res;
Chris Lattner24793662009-03-05 22:45:59 +000011307}
11308
11309/// HandleField - Analyze a field of a C struct or a C++ data member.
11310///
11311FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11312 SourceLocation DeclStart,
Richard Smithca523302012-06-10 03:12:00 +000011313 Declarator &D, Expr *BitWidth,
11314 InClassInitStyle InitStyle,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011315 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011316 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +000011317 SourceLocation Loc = DeclStart;
11318 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011319
John McCallbf1a0282010-06-04 23:28:52 +000011320 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11321 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +000011322 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011323 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +000011324
Douglas Gregore1862692010-12-15 23:18:36 +000011325 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11326 UPPC_DataMemberType)) {
11327 D.setInvalidType();
11328 T = Context.IntTy;
11329 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11330 }
11331 }
11332
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011333 // TR 18037 does not allow fields to be declared with address spaces.
11334 if (T.getQualifiers().hasAddressSpace()) {
11335 Diag(Loc, diag::err_field_with_address_space);
11336 D.setInvalidType();
11337 }
11338
Guy Benyeie6b9d802013-01-20 12:31:11 +000011339 // OpenCL 1.2 spec, s6.9 r:
11340 // The event type cannot be used to declare a structure or union field.
11341 if (LangOpts.OpenCL && T->isEventT()) {
11342 Diag(Loc, diag::err_event_t_struct_field);
11343 D.setInvalidType();
11344 }
11345
Richard Smithc7f81162013-03-18 22:52:47 +000011346 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +000011347
Richard Smithec642442013-04-12 22:46:28 +000011348 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11349 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11350 diag::err_invalid_thread)
11351 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011352
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011353 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +000011354 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011355 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11356 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +000011357 switch (Previous.getResultKind()) {
11358 case LookupResult::Found:
11359 case LookupResult::FoundUnresolvedValue:
11360 PrevDecl = Previous.getAsSingle<NamedDecl>();
11361 break;
11362
11363 case LookupResult::FoundOverloaded:
11364 PrevDecl = Previous.getRepresentativeDecl();
11365 break;
11366
11367 case LookupResult::NotFound:
11368 case LookupResult::NotFoundInCurrentInstantiation:
11369 case LookupResult::Ambiguous:
11370 break;
11371 }
11372 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +000011373
11374 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11375 // Maybe we will complain about the shadowed template parameter.
11376 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11377 // Just pretend that we didn't see the previous declaration.
11378 PrevDecl = 0;
11379 }
11380
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011381 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11382 PrevDecl = 0;
11383
Steve Naroffea218b82009-07-14 14:58:18 +000011384 bool Mutable
11385 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +000011386 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +000011387 FieldDecl *NewFD
Richard Smithca523302012-06-10 03:12:00 +000011388 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith7a614d82011-06-11 17:19:42 +000011389 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +000011390
11391 if (NewFD->isInvalidDecl())
11392 Record->setInvalidDecl();
11393
Douglas Gregor591dc842011-09-12 16:11:24 +000011394 if (D.getDeclSpec().isModulePrivateSpecified())
11395 NewFD->setModulePrivate();
11396
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011397 if (NewFD->isInvalidDecl() && PrevDecl) {
11398 // Don't introduce NewFD into scope; there's already something
11399 // with the same name in the same scope.
11400 } else if (II) {
11401 PushOnScopeChains(NewFD, S);
11402 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011403 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011404
11405 return NewFD;
11406}
11407
11408/// \brief Build a new FieldDecl and check its well-formedness.
11409///
11410/// This routine builds a new FieldDecl given the fields name, type,
11411/// record, etc. \p PrevDecl should refer to any previous declaration
11412/// with the same name and in the same scope as the field to be
11413/// created.
11414///
11415/// \returns a new FieldDecl.
11416///
Mike Stump1eb44332009-09-09 15:08:12 +000011417/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +000011418FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000011419 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011420 RecordDecl *Record, SourceLocation Loc,
Richard Smithca523302012-06-10 03:12:00 +000011421 bool Mutable, Expr *BitWidth,
11422 InClassInitStyle InitStyle,
Steve Naroffea218b82009-07-14 14:58:18 +000011423 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011424 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011425 Declarator *D) {
11426 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +000011427 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +000011428 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +000011429
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011430 // If we receive a broken type, recover by assuming 'int' and
11431 // marking this declaration as invalid.
11432 if (T.isNull()) {
11433 InvalidDecl = true;
11434 T = Context.IntTy;
11435 }
11436
Eli Friedman721e77d2009-12-07 00:22:08 +000011437 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011438 if (!EltTy->isDependentType()) {
11439 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11440 // Fields of incomplete type force their record to be invalid.
11441 Record->setInvalidDecl();
11442 InvalidDecl = true;
11443 } else {
11444 NamedDecl *Def;
11445 EltTy->isIncompleteType(&Def);
11446 if (Def && Def->isInvalidDecl()) {
11447 Record->setInvalidDecl();
11448 InvalidDecl = true;
11449 }
11450 }
John McCall2d7d2d92010-08-16 23:42:35 +000011451 }
Eli Friedman721e77d2009-12-07 00:22:08 +000011452
Joey Gouly617bb312013-01-17 17:35:00 +000011453 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11454 if (BitWidth && getLangOpts().OpenCL) {
11455 Diag(Loc, diag::err_opencl_bitfields);
11456 InvalidDecl = true;
11457 }
11458
Reid Spencer5f016e22007-07-11 17:01:13 +000011459 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11460 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +000011461 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011462 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +000011463 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011464
11465 TypeSourceInfo *FixedTInfo =
11466 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11467 SizeIsNegative,
11468 Oversized);
11469 if (FixedTInfo) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011470 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011471 TInfo = FixedTInfo;
11472 T = FixedTInfo->getType();
Eli Friedman1ca48132009-02-21 00:44:51 +000011473 } else {
11474 if (SizeIsNegative)
11475 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +000011476 else if (Oversized.getBoolValue())
11477 Diag(Loc, diag::err_array_too_large)
11478 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +000011479 else
11480 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +000011481 InvalidDecl = true;
11482 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011483 }
Mike Stump1eb44332009-09-09 15:08:12 +000011484
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011485 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +000011486 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11487 diag::err_abstract_type_in_decl,
11488 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011489 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +000011490
Eli Friedman1d954f62009-08-15 21:55:26 +000011491 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011492 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +000011493 if (!InvalidDecl && BitWidth) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011494 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11495 &ZeroWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011496 if (!BitWidth) {
11497 InvalidDecl = true;
11498 BitWidth = 0;
11499 ZeroWidth = false;
11500 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011501 }
Mike Stump1eb44332009-09-09 15:08:12 +000011502
John McCall4bde1e12010-06-04 08:34:12 +000011503 // Check that 'mutable' is consistent with the type of the declaration.
11504 if (!InvalidDecl && Mutable) {
11505 unsigned DiagID = 0;
11506 if (T->isReferenceType())
11507 DiagID = diag::err_mutable_reference;
11508 else if (T.isConstQualified())
11509 DiagID = diag::err_mutable_const;
11510
11511 if (DiagID) {
11512 SourceLocation ErrLoc = Loc;
11513 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11514 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11515 Diag(ErrLoc, DiagID);
11516 Mutable = false;
11517 InvalidDecl = true;
11518 }
11519 }
11520
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011521 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +000011522 BitWidth, Mutable, InitStyle);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011523 if (InvalidDecl)
11524 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +000011525
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011526 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11527 Diag(Loc, diag::err_duplicate_member) << II;
11528 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11529 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +000011530 }
11531
David Blaikie4e4d0842012-03-11 07:00:24 +000011532 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +000011533 if (Record->isUnion()) {
11534 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11535 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11536 if (RDecl->getDefinition()) {
11537 // C++ [class.union]p1: An object of a class with a non-trivial
11538 // constructor, a non-trivial copy constructor, a non-trivial
11539 // destructor, or a non-trivial copy assignment operator
11540 // cannot be a member of a union, nor can an array of such
11541 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +000011542 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +000011543 NewFD->setInvalidDecl();
11544 }
11545 }
11546
11547 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballman76eed422013-05-30 16:20:00 +000011548 // the program is ill-formed, except when compiling with MSVC extensions
11549 // enabled.
Anders Carlssondfdfc582010-11-07 19:13:55 +000011550 if (EltTy->isReferenceType()) {
Aaron Ballman76eed422013-05-30 16:20:00 +000011551 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11552 diag::ext_union_member_of_reference_type :
11553 diag::err_union_member_of_reference_type)
Anders Carlssondfdfc582010-11-07 19:13:55 +000011554 << NewFD->getDeclName() << EltTy;
Aaron Ballman76eed422013-05-30 16:20:00 +000011555 if (!getLangOpts().MicrosoftExt)
11556 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +000011557 }
11558 }
11559 }
11560
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011561 // FIXME: We need to pass in the attributes given an AST
11562 // representation, not a parser representation.
Richard Smithbe507b62013-02-01 08:12:08 +000011563 if (D) {
Douglas Gregor92eb7d82013-05-02 23:25:32 +000011564 // FIXME: The current scope is almost... but not entirely... correct here.
11565 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011566
Richard Smithbe507b62013-02-01 08:12:08 +000011567 if (NewFD->hasAttrs())
11568 CheckAlignasUnderalignment(NewFD);
11569 }
11570
John McCallf85e1932011-06-15 23:02:42 +000011571 // In auto-retain/release, infer strong retension for fields of
11572 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011573 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +000011574 NewFD->setInvalidDecl();
11575
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +000011576 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +000011577 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +000011578
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011579 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +000011580 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +000011581}
11582
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011583bool Sema::CheckNontrivialField(FieldDecl *FD) {
11584 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +000011585 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011586
Nick Lewyckydccd04d2013-06-25 23:22:23 +000011587 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11588 return false;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011589
11590 QualType EltTy = Context.getBaseElementType(FD->getType());
11591 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smithac713512012-12-08 02:53:02 +000011592 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011593 if (RDecl->getDefinition()) {
11594 // We check for copy constructors before constructors
11595 // because otherwise we'll never get complaints about
11596 // copy constructors.
11597
11598 CXXSpecialMember member = CXXInvalid;
Richard Smith426391c2012-11-16 00:53:38 +000011599 // We're required to check for any non-trivial constructors. Since the
11600 // implicit default constructor is suppressed if there are any
11601 // user-declared constructors, we just need to check that there is a
11602 // trivial default constructor and a trivial copy constructor. (We don't
11603 // worry about move constructors here, since this is a C++98 check.)
11604 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011605 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +000011606 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +000011607 member = CXXDefaultConstructor;
Richard Smith426391c2012-11-16 00:53:38 +000011608 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011609 member = CXXCopyAssignment;
Richard Smith426391c2012-11-16 00:53:38 +000011610 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011611 member = CXXDestructor;
11612
11613 if (member != CXXInvalid) {
Richard Smith80ad52f2013-01-02 11:42:31 +000011614 if (!getLangOpts().CPlusPlus11 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011615 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +000011616 // Objective-C++ ARC: it is an error to have a non-trivial field of
11617 // a union. However, system headers in Objective-C programs
11618 // occasionally have Objective-C lifetime objects within unions,
11619 // and rather than cause the program to fail, we make those
11620 // members unavailable.
11621 SourceLocation Loc = FD->getLocation();
11622 if (getSourceManager().isInSystemHeader(Loc)) {
11623 if (!FD->hasAttr<UnavailableAttr>())
11624 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011625 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011626 return false;
11627 }
11628 }
Richard Smithe7d7c392011-10-19 20:41:51 +000011629
Richard Smith80ad52f2013-01-02 11:42:31 +000011630 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithe7d7c392011-10-19 20:41:51 +000011631 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11632 diag::err_illegal_union_or_anon_struct_member)
11633 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smithac713512012-12-08 02:53:02 +000011634 DiagnoseNontrivial(RDecl, member);
Richard Smith80ad52f2013-01-02 11:42:31 +000011635 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011636 }
11637 }
11638 }
Richard Smithac713512012-12-08 02:53:02 +000011639
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011640 return false;
11641}
11642
Mike Stump1eb44332009-09-09 15:08:12 +000011643/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011644/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011645static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011646TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +000011647 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +000011648 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +000011649 case tok::objc_private: return ObjCIvarDecl::Private;
11650 case tok::objc_public: return ObjCIvarDecl::Public;
11651 case tok::objc_protected: return ObjCIvarDecl::Protected;
11652 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +000011653 }
11654}
11655
Mike Stump1eb44332009-09-09 15:08:12 +000011656/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +000011657/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +000011658Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +000011659 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011660 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +000011661 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +000011662
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011663 IdentifierInfo *II = D.getIdentifier();
11664 Expr *BitWidth = (Expr*)BitfieldWidth;
11665 SourceLocation Loc = DeclStart;
11666 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011667
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011668 // FIXME: Unnamed fields can be handled in various different ways, for
11669 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +000011670
John McCallbf1a0282010-06-04 23:28:52 +000011671 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11672 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000011673
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011674 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +000011675 // 6.7.2.1p3, 6.7.2.1p4
Warren Huntb2969b12013-10-11 20:19:00 +000011676 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011677 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +000011678 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011679 } else {
11680 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +000011681
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011682 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +000011683
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011684 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011685 if (T->isReferenceType()) {
11686 Diag(Loc, diag::err_ivar_reference_type);
11687 D.setInvalidType();
11688 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011689 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11690 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011691 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +000011692 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011693 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011694 }
Mike Stump1eb44332009-09-09 15:08:12 +000011695
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011696 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +000011697 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011698 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11699 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011700 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011701 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +000011702 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11703 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +000011704 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +000011705 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011706 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011707 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011708 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +000011709 EnclosingContext = IMPDecl->getClassInterface();
11710 assert(EnclosingContext && "Implementation has no class interface!");
11711 }
11712 else
11713 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011714 } else {
11715 if (ObjCCategoryDecl *CDecl =
11716 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011717 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011718 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +000011719 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011720 }
11721 }
Daniel Dunbara19331f2010-04-02 18:29:09 +000011722 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011723 }
Mike Stump1eb44332009-09-09 15:08:12 +000011724
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011725 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011726 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11727 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +000011728 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +000011729
Douglas Gregor72de6672009-01-08 20:45:30 +000011730 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000011731 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +000011732 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011733 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +000011734 && !isa<TagDecl>(PrevDecl)) {
11735 Diag(Loc, diag::err_duplicate_member) << II;
11736 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11737 NewID->setInvalidDecl();
11738 }
11739 }
11740
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011741 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011742 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +000011743
Chris Lattnereaaebc72009-04-25 08:06:05 +000011744 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011745 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011746
John McCallf85e1932011-06-15 23:02:42 +000011747 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011748 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +000011749 NewID->setInvalidDecl();
11750
Douglas Gregor591dc842011-09-12 16:11:24 +000011751 if (D.getDeclSpec().isModulePrivateSpecified())
11752 NewID->setModulePrivate();
11753
Douglas Gregor72de6672009-01-08 20:45:30 +000011754 if (II) {
11755 // FIXME: When interfaces are DeclContexts, we'll need to add
11756 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +000011757 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +000011758 IdResolver.AddDecl(NewID);
11759 }
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011760
John McCall260611a2012-06-20 06:18:46 +000011761 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011762 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniandc3eb6a2012-05-15 17:43:16 +000011763 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011764
John McCalld226f652010-08-21 09:40:31 +000011765 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011766}
11767
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011768/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosed4582b82013-04-03 01:39:23 +000011769/// class and class extensions. For every class \@interface and class
11770/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011771/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011772void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011773 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall260611a2012-06-20 06:18:46 +000011774 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011775 return;
11776
11777 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11778 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11779
Richard Smitha6b8b2c2011-10-10 18:28:20 +000011780 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011781 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011782 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011783 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011784 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011785 if (!CD->IsClassExtension())
11786 return;
11787 }
11788 // No need to add this to end of @implementation.
11789 else
11790 return;
11791 }
11792 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011793 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11794 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011795
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011796 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011797 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011798 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011799 Context.getTrivialTypeSourceInfo(Context.CharTy,
11800 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011801 ObjCIvarDecl::Private, BW,
11802 true);
11803 AllIvarDecls.push_back(Ivar);
11804}
11805
Robert Wilhelm834c0582013-08-09 18:02:13 +000011806void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11807 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11808 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +000011809 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +000011810
Eric Christopher6dba4a12012-07-19 22:22:51 +000011811 // If this is an Objective-C @implementation or category and we have
11812 // new fields here we should reset the layout of the interface since
11813 // it will now change.
11814 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11815 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11816 switch (DC->getKind()) {
11817 default: break;
11818 case Decl::ObjCCategory:
11819 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11820 break;
11821 case Decl::ObjCImplementation:
11822 Context.
11823 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11824 break;
11825 }
11826 }
11827
Eli Friedman11e70d72012-02-07 05:00:47 +000011828 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11829
11830 // Start counting up the number of named members; make sure to include
11831 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +000011832 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +000011833 if (Record) {
11834 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11835 e = Record->decls_end(); i != e; i++) {
11836 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11837 if (IFD->getDeclName())
11838 ++NumNamedMembers;
11839 }
11840 }
11841
11842 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011843 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011844
John McCallf85e1932011-06-15 23:02:42 +000011845 bool ARCErrReported = false;
Robert Wilhelm834c0582013-08-09 18:02:13 +000011846 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie77b6de02011-09-22 02:58:26 +000011847 i != end; ++i) {
11848 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +000011849
Reid Spencer5f016e22007-07-11 17:01:13 +000011850 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +000011851 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011852
Douglas Gregor72de6672009-01-08 20:45:30 +000011853 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011854 // Remember all fields written by the user.
11855 RecFields.push_back(FD);
11856 }
Mike Stump1eb44332009-09-09 15:08:12 +000011857
Chris Lattner24793662009-03-05 22:45:59 +000011858 // If the field is already invalid for some reason, don't emit more
11859 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +000011860 if (FD->isInvalidDecl()) {
11861 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +000011862 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +000011863 }
Mike Stump1eb44332009-09-09 15:08:12 +000011864
Douglas Gregore7450f52009-03-24 19:52:54 +000011865 // C99 6.7.2.1p2:
11866 // A structure or union shall not contain a member with
11867 // incomplete or function type (hence, a structure shall not
11868 // contain an instance of itself, but may contain a pointer to
11869 // an instance of itself), except that the last member of a
11870 // structure with more than one named member may have incomplete
11871 // array type; such a structure (and any union containing,
11872 // possibly recursively, a member that is such a structure)
11873 // shall not be a member of a structure or an element of an
11874 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +000011875 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011876 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011877 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011878 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011879 FD->setInvalidDecl();
11880 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011881 continue;
Francois Pichet09246182010-09-15 00:14:08 +000011882 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +000011883 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +000011884 ((getLangOpts().MicrosoftExt ||
11885 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +000011886 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011887 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011888 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +000011889 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +000011890 // as the sole element of a struct/class.
David Majnemer633c0c22013-11-02 10:38:05 +000011891 unsigned DiagID = 0;
11892 if (Record->isUnion())
11893 DiagID = getLangOpts().MicrosoftExt
11894 ? diag::ext_flexible_array_union_ms
11895 : getLangOpts().CPlusPlus
11896 ? diag::ext_flexible_array_union_gnu
11897 : diag::err_flexible_array_union;
11898 else if (Fields.size() == 1)
11899 DiagID = getLangOpts().MicrosoftExt
11900 ? diag::ext_flexible_array_empty_aggregate_ms
11901 : getLangOpts().CPlusPlus
11902 ? diag::ext_flexible_array_empty_aggregate_gnu
11903 : NumNamedMembers < 1
11904 ? diag::err_flexible_array_empty_aggregate
11905 : 0;
11906
11907 if (DiagID)
11908 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11909 << Record->getTagKind();
David Majnemer3a665572013-11-02 11:19:13 +000011910 // While the layout of types that contain virtual bases is not specified
11911 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11912 // virtual bases after the derived members. This would make a flexible
11913 // array member declared at the end of an object not adjacent to the end
11914 // of the type.
11915 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11916 if (RD->getNumVBases() != 0)
11917 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11918 << FD->getDeclName() << Record->getTagKind();
David Majnemer633c0c22013-11-02 10:38:05 +000011919 if (!getLangOpts().C99)
11920 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11921 << FD->getDeclName() << Record->getTagKind();
11922
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011923 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +000011924 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011925 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +000011926 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011927 FD->setInvalidDecl();
11928 EnclosingDecl->setInvalidDecl();
11929 continue;
11930 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011931 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +000011932 if (Record)
11933 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +000011934 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +000011935 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +000011936 diag::err_field_incomplete)) {
11937 // Incomplete type
11938 FD->setInvalidDecl();
11939 EnclosingDecl->setInvalidDecl();
11940 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +000011941 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011942 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11943 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000011944 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011945 Record->setHasFlexibleArrayMember(true);
11946 } else {
11947 // If this is a struct/class and this is not the last element, reject
11948 // it. Note that GCC supports variable sized arrays in the middle of
11949 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +000011950 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +000011951 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +000011952 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +000011953 else {
11954 // We support flexible arrays at the end of structs in
11955 // other structs as an extension.
11956 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11957 << FD->getDeclName();
11958 if (Record)
11959 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011960 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011961 }
11962 }
Fariborz Jahanian7f90b532012-08-16 22:38:41 +000011963 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11964 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11965 diag::err_abstract_type_in_decl,
11966 AbstractIvarType)) {
11967 // Ivars can not have abstract class types
11968 FD->setInvalidDecl();
11969 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000011970 if (Record && FDTTy->getDecl()->hasObjectMember())
11971 Record->setHasObjectMember(true);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011972 if (Record && FDTTy->getDecl()->hasVolatileMember())
11973 Record->setHasVolatileMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +000011974 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011975 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +000011976 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11977 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11978 QualType T = Context.getObjCObjectPointerType(FD->getType());
11979 FD->setType(T);
Douglas Gregor4581d452013-01-28 19:08:09 +000011980 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11981 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11982 // It's an error in ARC if a field has lifetime.
11983 // We don't want to report this in a system header, though,
11984 // so we just make the field unavailable.
11985 // FIXME: that's really not sufficient; we need to make the type
11986 // itself invalid to, say, initialize or copy.
11987 QualType T = FD->getType();
11988 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11989 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11990 SourceLocation loc = FD->getLocation();
11991 if (getSourceManager().isInSystemHeader(loc)) {
11992 if (!FD->hasAttr<UnavailableAttr>()) {
11993 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11994 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011995 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011996 } else {
11997 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregorbde67cf2013-01-28 20:13:44 +000011998 << T->isBlockPointerType() << Record->getTagKind();
John McCallf85e1932011-06-15 23:02:42 +000011999 }
Douglas Gregor4581d452013-01-28 19:08:09 +000012000 ARCErrReported = true;
John McCallf85e1932011-06-15 23:02:42 +000012001 }
Douglas Gregor4581d452013-01-28 19:08:09 +000012002 } else if (getLangOpts().ObjC1 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012003 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +000012004 Record && !Record->hasObjectMember()) {
Douglas Gregor4581d452013-01-28 19:08:09 +000012005 if (FD->getType()->isObjCObjectPointerType() ||
12006 FD->getType().isObjCGCStrong())
12007 Record->setHasObjectMember(true);
12008 else if (Context.getAsArrayType(FD->getType())) {
12009 QualType BaseType = Context.getBaseElementType(FD->getType());
12010 if (BaseType->isRecordType() &&
12011 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCallf85e1932011-06-15 23:02:42 +000012012 Record->setHasObjectMember(true);
Douglas Gregor4581d452013-01-28 19:08:09 +000012013 else if (BaseType->isObjCObjectPointerType() ||
12014 BaseType.isObjCGCStrong())
12015 Record->setHasObjectMember(true);
John McCallf85e1932011-06-15 23:02:42 +000012016 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +000012017 }
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000012018 if (Record && FD->getType().isVolatileQualified())
12019 Record->setHasVolatileMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000012020 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +000012021 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +000012022 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +000012023 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000012024
Reid Spencer5f016e22007-07-11 17:01:13 +000012025 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +000012026 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012027 bool Completed = false;
12028 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12029 if (!CXXRecord->isInvalidDecl()) {
12030 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000012031 for (CXXRecordDecl::conversion_iterator
12032 I = CXXRecord->conversion_begin(),
12033 E = CXXRecord->conversion_end(); I != E; ++I)
12034 I.setAccess((*I)->getAccess());
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012035
12036 if (!CXXRecord->isDependentType()) {
Peter Collingbournef51cfb82013-05-20 14:12:25 +000012037 if (CXXRecord->hasUserDeclaredDestructor()) {
12038 // Adjust user-defined destructor exception spec.
12039 if (getLangOpts().CPlusPlus11)
12040 AdjustDestructorExceptionSpec(CXXRecord,
12041 CXXRecord->getDestructor());
12042
12043 // The Microsoft ABI requires that we perform the destructor body
12044 // checks (i.e. operator delete() lookup) at every declaration, as
12045 // any translation unit may need to emit a deleting destructor.
12046 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12047 CheckDestructor(CXXRecord->getDestructor());
12048 }
Sebastian Redl0ee33912011-05-19 05:13:44 +000012049
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012050 // Add any implicitly-declared members to this class.
12051 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12052
12053 // If we have virtual base classes, we may end up finding multiple
12054 // final overriders for a given virtual function. Check for this
12055 // problem now.
12056 if (CXXRecord->getNumVBases()) {
12057 CXXFinalOverriderMap FinalOverriders;
12058 CXXRecord->getFinalOverriders(FinalOverriders);
12059
12060 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12061 MEnd = FinalOverriders.end();
12062 M != MEnd; ++M) {
12063 for (OverridingMethods::iterator SO = M->second.begin(),
12064 SOEnd = M->second.end();
12065 SO != SOEnd; ++SO) {
12066 assert(SO->second.size() > 0 &&
12067 "Virtual function without overridding functions?");
12068 if (SO->second.size() == 1)
12069 continue;
12070
12071 // C++ [class.virtual]p2:
12072 // In a derived class, if a virtual member function of a base
12073 // class subobject has more than one final overrider the
12074 // program is ill-formed.
12075 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divacky31ba6132012-09-06 15:59:27 +000012076 << (const NamedDecl *)M->first << Record;
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012077 Diag(M->first->getLocation(),
12078 diag::note_overridden_virtual_function);
12079 for (OverridingMethods::overriding_iterator
12080 OM = SO->second.begin(),
12081 OMEnd = SO->second.end();
12082 OM != OMEnd; ++OM)
12083 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divacky31ba6132012-09-06 15:59:27 +000012084 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012085
12086 Record->setInvalidDecl();
12087 }
12088 }
12089 CXXRecord->completeDefinition(&FinalOverriders);
12090 Completed = true;
12091 }
12092 }
12093 }
12094 }
12095
12096 if (!Completed)
12097 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +000012098
Richard Smithbe507b62013-02-01 08:12:08 +000012099 if (Record->hasAttrs())
12100 CheckAlignasUnderalignment(Record);
Serge Pavlov122e6012013-06-08 13:29:58 +000012101
Serge Pavlov142ab062013-11-14 02:13:03 +000012102 // Check if the structure/union declaration is a type that can have zero
12103 // size in C. For C this is a language extension, for C++ it may cause
12104 // compatibility problems.
12105 bool CheckForZeroSize;
Serge Pavlov122e6012013-06-08 13:29:58 +000012106 if (!getLangOpts().CPlusPlus) {
Serge Pavlov142ab062013-11-14 02:13:03 +000012107 CheckForZeroSize = true;
12108 } else {
12109 // For C++ filter out types that cannot be referenced in C code.
12110 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12111 CheckForZeroSize =
12112 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12113 !CXXRecord->isDependentType() &&
12114 CXXRecord->isCLike();
12115 }
12116 if (CheckForZeroSize) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012117 bool ZeroSize = true;
Serge Pavlov0dcea352013-06-17 17:18:51 +000012118 bool IsEmpty = true;
12119 unsigned NonBitFields = 0;
Serge Pavlov122e6012013-06-08 13:29:58 +000012120 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlov0dcea352013-06-17 17:18:51 +000012121 E = Record->field_end();
12122 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12123 IsEmpty = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012124 if (I->isUnnamedBitfield()) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012125 if (I->getBitWidthValue(Context) > 0)
12126 ZeroSize = false;
12127 } else {
Serge Pavlov0dcea352013-06-17 17:18:51 +000012128 ++NonBitFields;
12129 QualType FieldType = I->getType();
12130 if (FieldType->isIncompleteType() ||
12131 !Context.getTypeSizeInChars(FieldType).isZero())
12132 ZeroSize = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012133 }
12134 }
12135
Serge Pavlov142ab062013-11-14 02:13:03 +000012136 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12137 // allowed in C++, but warn if its declaration is inside
12138 // extern "C" block.
12139 if (ZeroSize) {
12140 Diag(RecLoc, getLangOpts().CPlusPlus ?
12141 diag::warn_zero_size_struct_union_in_extern_c :
12142 diag::warn_zero_size_struct_union_compat)
12143 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12144 }
Serge Pavlov122e6012013-06-08 13:29:58 +000012145
Serge Pavlov142ab062013-11-14 02:13:03 +000012146 // Structs without named members are extension in C (C99 6.7.2.1p7),
12147 // but are accepted by GCC.
12148 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12149 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12150 diag::ext_no_named_members_in_struct_union)
12151 << Record->isUnion();
Serge Pavlov122e6012013-06-08 13:29:58 +000012152 }
12153 }
Chris Lattnere1e79852008-02-06 00:51:33 +000012154 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +000012155 ObjCIvarDecl **ClsFields =
12156 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +000012157 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +000012158 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012159 // Add ivar's to class's DeclContext.
12160 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12161 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012162 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012163 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +000012164 // Must enforce the rule that ivars in the base classes may not be
12165 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +000012166 if (ID->getSuperClass())
12167 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +000012168 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +000012169 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000012170 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012171 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12172 // Ivar declared in @implementation never belongs to the implementation.
12173 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +000012174 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +000012175 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012176 IMPDecl->setIvarLBraceLoc(LBrac);
12177 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012178 } else if (ObjCCategoryDecl *CDecl =
12179 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012180 // case of ivars in class extension; all other cases have been
12181 // reported as errors elsewhere.
12182 // FIXME. Class extension does not have a LocEnd field.
12183 // CDecl->setLocEnd(RBrac);
12184 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012185 // Diagnose redeclaration of private ivars.
12186 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012187 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012188 if (IDecl) {
12189 if (const ObjCIvarDecl *ClsIvar =
12190 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12191 Diag(ClsFields[i]->getLocation(),
12192 diag::err_duplicate_ivar_declaration);
12193 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12194 continue;
12195 }
Douglas Gregord3297242013-01-16 23:00:23 +000012196 for (ObjCInterfaceDecl::known_extensions_iterator
12197 Ext = IDecl->known_extensions_begin(),
12198 ExtEnd = IDecl->known_extensions_end();
12199 Ext != ExtEnd; ++Ext) {
12200 if (const ObjCIvarDecl *ClsExtIvar
12201 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012202 Diag(ClsFields[i]->getLocation(),
12203 diag::err_duplicate_ivar_declaration);
12204 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12205 continue;
12206 }
12207 }
12208 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012209 ClsFields[i]->setLexicalDeclContext(CDecl);
12210 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012211 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012212 CDecl->setIvarLBraceLoc(LBrac);
12213 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +000012214 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +000012215 }
Daniel Dunbar7d076642008-10-03 17:33:35 +000012216
12217 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000012218 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +000012219}
12220
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012221/// \brief Determine whether the given integral value is representable within
12222/// the given type T.
12223static bool isRepresentableIntegerValue(ASTContext &Context,
12224 llvm::APSInt &Value,
12225 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012226 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +000012227 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012228
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012229 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +000012230 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012231 --BitWidth;
12232 return Value.getActiveBits() <= BitWidth;
12233 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012234 return Value.getMinSignedBits() <= BitWidth;
12235}
12236
12237// \brief Given an integral type, return the next larger integral type
12238// (or a NULL type of no such type exists).
12239static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12240 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12241 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012242 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012243 const unsigned NumTypes = 4;
12244 QualType SignedIntegralTypes[NumTypes] = {
12245 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12246 };
12247 QualType UnsignedIntegralTypes[NumTypes] = {
12248 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12249 Context.UnsignedLongLongTy
12250 };
12251
12252 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +000012253 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12254 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012255 for (unsigned I = 0; I != NumTypes; ++I)
12256 if (Context.getTypeSize(Types[I]) > BitWidth)
12257 return Types[I];
12258
12259 return QualType();
12260}
12261
Douglas Gregor879fd492009-03-17 19:05:46 +000012262EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12263 EnumConstantDecl *LastEnumConst,
12264 SourceLocation IdLoc,
12265 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +000012266 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012267 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012268 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +000012269 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +000012270
12271 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12272 Val = 0;
12273
Eli Friedman19efa3e2011-12-06 00:10:34 +000012274 if (Val)
12275 Val = DefaultLvalueConversion(Val).take();
12276
Douglas Gregor4912c342009-11-06 00:03:12 +000012277 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012278 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +000012279 EltTy = Context.DependentTy;
12280 else {
Douglas Gregor4912c342009-11-06 00:03:12 +000012281 SourceLocation ExpLoc;
Richard Smith80ad52f2013-01-02 11:42:31 +000012282 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012283 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012284 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12285 // constant-expression in the enumerator-definition shall be a converted
12286 // constant expression of the underlying type.
12287 EltTy = Enum->getIntegerType();
12288 ExprResult Converted =
12289 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12290 CCEK_Enumerator);
12291 if (Converted.isInvalid())
12292 Val = 0;
12293 else
12294 Val = Converted.take();
12295 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +000012296 !(Val = VerifyIntegerConstantExpression(Val,
12297 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012298 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +000012299 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012300 if (Enum->isFixed()) {
12301 EltTy = Enum->getIntegerType();
12302
Richard Smith8ef7b202012-01-18 23:55:52 +000012303 // In Obj-C and Microsoft mode, require the enumeration value to be
12304 // representable in the underlying type of the enumeration. In C++11,
12305 // we perform a non-narrowing conversion as part of converted constant
12306 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +000012307 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012308 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +000012309 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +000012310 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +000012311 } else
12312 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +000012313 } else
John Wiegley429bb272011-04-08 18:41:53 +000012314 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +000012315 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012316 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012317 // If the underlying type is not fixed, the type of each enumerator
12318 // is the type of its initializing value:
12319 // - If an initializer is specified for an enumerator, the
12320 // initializing value has the same type as the expression.
12321 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +000012322 } else {
12323 // C99 6.7.2.2p2:
12324 // The expression that defines the value of an enumeration constant
12325 // shall be an integer constant expression that has a value
12326 // representable as an int.
12327
12328 // Complain if the value is not representable in an int.
12329 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12330 Diag(IdLoc, diag::ext_enum_value_not_int)
12331 << EnumVal.toString(10) << Val->getSourceRange()
12332 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12333 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12334 // Force the type of the expression to 'int'.
12335 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12336 }
12337 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012338 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012339 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012340 }
12341 }
Mike Stump1eb44332009-09-09 15:08:12 +000012342
Douglas Gregor879fd492009-03-17 19:05:46 +000012343 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012344 if (Enum->isDependentType())
12345 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012346 else if (!LastEnumConst) {
12347 // C++0x [dcl.enum]p5:
12348 // If the underlying type is not fixed, the type of each enumerator
12349 // is the type of its initializing value:
12350 // - If no initializer is specified for the first enumerator, the
12351 // initializing value has an unspecified integral type.
12352 //
12353 // GCC uses 'int' for its unspecified integral type, as does
12354 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012355 if (Enum->isFixed()) {
12356 EltTy = Enum->getIntegerType();
12357 }
12358 else {
12359 EltTy = Context.IntTy;
12360 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012361 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000012362 // Assign the last value + 1.
12363 EnumVal = LastEnumConst->getInitVal();
12364 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012365 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000012366
12367 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012368 if (EnumVal < LastEnumConst->getInitVal()) {
12369 // C++0x [dcl.enum]p5:
12370 // If the underlying type is not fixed, the type of each enumerator
12371 // is the type of its initializing value:
12372 //
12373 // - Otherwise the type of the initializing value is the same as
12374 // the type of the initializing value of the preceding enumerator
12375 // unless the incremented value is not representable in that type,
12376 // in which case the type is an unspecified integral type
12377 // sufficient to contain the incremented value. If no such type
12378 // exists, the program is ill-formed.
12379 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012380 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012381 // There is no integral type larger enough to represent this
12382 // value. Complain, then allow the value to wrap around.
12383 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000012384 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012385 ++EnumVal;
12386 if (Enum->isFixed())
12387 // When the underlying type is fixed, this is ill-formed.
12388 Diag(IdLoc, diag::err_enumerator_wrapped)
12389 << EnumVal.toString(10)
12390 << EltTy;
12391 else
12392 Diag(IdLoc, diag::warn_enumerator_too_large)
12393 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012394 } else {
12395 EltTy = T;
12396 }
12397
12398 // Retrieve the last enumerator's value, extent that type to the
12399 // type that is supposed to be large enough to represent the incremented
12400 // value, then increment.
12401 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000012402 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000012403 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012404 ++EnumVal;
12405
12406 // If we're not in C++, diagnose the overflow of enumerator values,
12407 // which in C99 means that the enumerator value is not representable in
12408 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12409 // permits enumerator values that are representable in some larger
12410 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000012411 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012412 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000012413 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012414 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12415 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12416 Diag(IdLoc, diag::ext_enum_value_not_int)
12417 << EnumVal.toString(10) << 1;
12418 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012419 }
12420 }
Mike Stump1eb44332009-09-09 15:08:12 +000012421
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012422 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012423 // Make the enumerator value match the signedness and size of the
12424 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000012425 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000012426 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012427 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012428
Douglas Gregor879fd492009-03-17 19:05:46 +000012429 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000012430 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000012431}
12432
12433
John McCall5b629aa2010-10-22 23:36:17 +000012434Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12435 SourceLocation IdLoc, IdentifierInfo *Id,
12436 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000012437 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000012438 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000012439 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000012440 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000012441
Chris Lattner31e05722007-08-26 06:24:45 +000012442 // The scope passed in may not be a decl scope. Zip up the scope tree until
12443 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000012444 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000012445
Reid Spencer5f016e22007-07-11 17:01:13 +000012446 // Verify that there isn't already something declared with this name in this
12447 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000012448 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000012449 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000012450 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000012451 // Maybe we will complain about the shadowed template parameter.
12452 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12453 // Just pretend that we didn't see the previous declaration.
12454 PrevDecl = 0;
12455 }
12456
12457 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012458 // When in C++, we may get a TagDecl with the same name; in this case the
12459 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000012460 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012461 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000012462 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012463 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000012464 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000012465 else
Chris Lattner3c73c412008-11-19 08:23:25 +000012466 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000012467 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000012468 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000012469 }
12470 }
12471
Aaron Ballmanf8167872012-07-19 03:12:23 +000012472 // C++ [class.mem]p15:
12473 // If T is the name of a class, then each of the following shall have a name
12474 // different from T:
12475 // - every enumerator of every member of class T that is an unscoped
12476 // enumerated type
Douglas Gregora6e937c2010-10-15 13:21:21 +000012477 if (CXXRecordDecl *Record
12478 = dyn_cast<CXXRecordDecl>(
12479 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballmanf8167872012-07-19 03:12:23 +000012480 if (!TheEnumDecl->isScoped() &&
12481 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregora6e937c2010-10-15 13:21:21 +000012482 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12483
John McCall5b629aa2010-10-22 23:36:17 +000012484 EnumConstantDecl *New =
12485 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000012486
John McCall92f88312010-01-23 00:46:32 +000012487 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000012488 // Process attributes.
12489 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12490
12491 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000012492 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000012493 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000012494 }
Douglas Gregor45579f52008-12-17 02:04:30 +000012495
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000012496 ActOnDocumentableDecl(New);
12497
John McCalld226f652010-08-21 09:40:31 +000012498 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000012499}
12500
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012501// Returns true when the enum initial expression does not trigger the
12502// duplicate enum warning. A few common cases are exempted as follows:
12503// Element2 = Element1
12504// Element2 = Element1 + 1
12505// Element2 = Element1 - 1
12506// Where Element2 and Element1 are from the same enum.
12507static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12508 Expr *InitExpr = ECD->getInitExpr();
12509 if (!InitExpr)
12510 return true;
12511 InitExpr = InitExpr->IgnoreImpCasts();
12512
12513 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12514 if (!BO->isAdditiveOp())
12515 return true;
12516 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12517 if (!IL)
12518 return true;
12519 if (IL->getValue() != 1)
12520 return true;
12521
12522 InitExpr = BO->getLHS();
12523 }
12524
12525 // This checks if the elements are from the same enum.
12526 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12527 if (!DRE)
12528 return true;
12529
12530 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12531 if (!EnumConstant)
12532 return true;
12533
12534 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12535 Enum)
12536 return true;
12537
12538 return false;
12539}
12540
12541struct DupKey {
12542 int64_t val;
12543 bool isTombstoneOrEmptyKey;
12544 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12545 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12546};
12547
12548static DupKey GetDupKey(const llvm::APSInt& Val) {
12549 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12550 false);
12551}
12552
12553struct DenseMapInfoDupKey {
12554 static DupKey getEmptyKey() { return DupKey(0, true); }
12555 static DupKey getTombstoneKey() { return DupKey(1, true); }
12556 static unsigned getHashValue(const DupKey Key) {
12557 return (unsigned)(Key.val * 37);
12558 }
12559 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12560 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12561 LHS.val == RHS.val;
12562 }
12563};
12564
12565// Emits a warning when an element is implicitly set a value that
12566// a previous element has already been set to.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012567static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12568 EnumDecl *Enum,
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012569 QualType EnumType) {
12570 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12571 Enum->getLocation()) ==
12572 DiagnosticsEngine::Ignored)
12573 return;
12574 // Avoid anonymous enums
12575 if (!Enum->getIdentifier())
12576 return;
12577
12578 // Only check for small enums.
12579 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12580 return;
12581
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012582 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12583 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012584
12585 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12586 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12587 ValueToVectorMap;
12588
12589 DuplicatesVector DupVector;
12590 ValueToVectorMap EnumMap;
12591
12592 // Populate the EnumMap with all values represented by enum constants without
12593 // an initialier.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012594 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramerefac8da2013-04-07 14:10:40 +000012595 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012596
12597 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12598 // this constant. Skip this enum since it may be ill-formed.
12599 if (!ECD) {
12600 return;
12601 }
12602
12603 if (ECD->getInitExpr())
12604 continue;
12605
12606 DupKey Key = GetDupKey(ECD->getInitVal());
12607 DeclOrVector &Entry = EnumMap[Key];
12608
12609 // First time encountering this value.
12610 if (Entry.isNull())
12611 Entry = ECD;
12612 }
12613
12614 // Create vectors for any values that has duplicates.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012615 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012616 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12617 if (!ValidDuplicateEnum(ECD, Enum))
12618 continue;
12619
12620 DupKey Key = GetDupKey(ECD->getInitVal());
12621
12622 DeclOrVector& Entry = EnumMap[Key];
12623 if (Entry.isNull())
12624 continue;
12625
12626 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12627 // Ensure constants are different.
12628 if (D == ECD)
12629 continue;
12630
12631 // Create new vector and push values onto it.
12632 ECDVector *Vec = new ECDVector();
12633 Vec->push_back(D);
12634 Vec->push_back(ECD);
12635
12636 // Update entry to point to the duplicates vector.
12637 Entry = Vec;
12638
12639 // Store the vector somewhere we can consult later for quick emission of
12640 // diagnostics.
12641 DupVector.push_back(Vec);
12642 continue;
12643 }
12644
12645 ECDVector *Vec = Entry.get<ECDVector*>();
12646 // Make sure constants are not added more than once.
12647 if (*Vec->begin() == ECD)
12648 continue;
12649
12650 Vec->push_back(ECD);
12651 }
12652
12653 // Emit diagnostics.
12654 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12655 DupVectorEnd = DupVector.end();
12656 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12657 ECDVector *Vec = *DupVectorIter;
12658 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12659
12660 // Emit warning for one enum constant.
12661 ECDVector::iterator I = Vec->begin();
12662 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12663 << (*I)->getName() << (*I)->getInitVal().toString(10)
12664 << (*I)->getSourceRange();
12665 ++I;
12666
12667 // Emit one note for each of the remaining enum constants with
12668 // the same value.
12669 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12670 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12671 << (*I)->getName() << (*I)->getInitVal().toString(10)
12672 << (*I)->getSourceRange();
12673 delete Vec;
12674 }
12675}
12676
Mike Stumpc6e35aa2009-05-16 07:06:02 +000012677void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000012678 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012679 ArrayRef<Decl *> Elements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012680 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000012681 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000012682 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012683
12684 if (Attr)
12685 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000012686
Eli Friedmaned0716b2009-12-11 01:34:50 +000012687 if (Enum->isDependentType()) {
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012688 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012689 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012690 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012691 if (!ECD) continue;
12692
12693 ECD->setType(EnumType);
12694 }
12695
John McCall1b5a6182010-05-06 08:49:23 +000012696 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012697 return;
12698 }
12699
Chris Lattnere37f0be2007-08-28 05:10:31 +000012700 // TODO: If the result value doesn't fit in an int, it must be a long or long
12701 // long value. ISO C does not support this, but GCC does as an extension,
12702 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012703 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12704 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12705 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012706
Chris Lattnerac609682007-08-28 06:15:15 +000012707 // Verify that all the values are okay, compute the size of the values, and
12708 // reverse the list.
12709 unsigned NumNegativeBits = 0;
12710 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000012711
Chris Lattnerac609682007-08-28 06:15:15 +000012712 // Keep track of whether all elements have type int.
12713 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000012714
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012715 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012716 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012717 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000012718 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000012719
Chris Lattner211a30e2007-08-28 05:27:00 +000012720 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000012721
Chris Lattnerac609682007-08-28 06:15:15 +000012722 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000012723 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000012724 NumPositiveBits = std::max(NumPositiveBits,
12725 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000012726 else
Chris Lattner21dd8212008-01-14 21:47:29 +000012727 NumNegativeBits = std::max(NumNegativeBits,
12728 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000012729
Chris Lattnerac609682007-08-28 06:15:15 +000012730 // Keep track of whether every enum element has type int (very commmon).
12731 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000012732 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000012733 }
Mike Stump1eb44332009-09-09 15:08:12 +000012734
Chris Lattnerac609682007-08-28 06:15:15 +000012735 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000012736 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012737 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012738
John McCall842aef82009-12-09 09:09:27 +000012739 // C++0x N3000 [conv.prom]p3:
12740 // An rvalue of an unscoped enumeration type whose underlying
12741 // type is not fixed can be converted to an rvalue of the first
12742 // of the following types that can represent all the values of
12743 // the enumeration: int, unsigned int, long int, unsigned long
12744 // int, long long int, or unsigned long long int.
12745 // C99 6.4.4.3p2:
12746 // An identifier declared as an enumeration constant has type int.
12747 // The C99 rule is modified by a gcc extension
12748 QualType BestPromotionType;
12749
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012750 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000012751 // -fshort-enums is the equivalent to specifying the packed attribute on all
12752 // enum definitions.
12753 if (LangOpts.ShortEnums)
12754 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012755
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012756 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000012757 BestType = Enum->getIntegerType();
12758 if (BestType->isPromotableIntegerType())
12759 BestPromotionType = Context.getPromotedIntegerType(BestType);
12760 else
12761 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000012762 // We don't need to set BestWidth, because BestType is going to be the type
12763 // of the enumerators, but we do anyway because otherwise some compilers
12764 // warn that it might be used uninitialized.
12765 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012766 }
12767 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000012768 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000012769 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012770 // If it's packed, check also if it fits a char or a short.
12771 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012772 BestType = Context.SignedCharTy;
12773 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000012774 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012775 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012776 BestType = Context.ShortTy;
12777 BestWidth = ShortWidth;
12778 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012779 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012780 BestWidth = IntWidth;
12781 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012782 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012783
John McCall842aef82009-12-09 09:09:27 +000012784 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012785 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000012786 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012787 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012788
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012789 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000012790 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12791 BestType = Context.LongLongTy;
12792 }
12793 }
John McCall842aef82009-12-09 09:09:27 +000012794 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000012795 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012796 // If there is no negative value, figure out the smallest type that fits
12797 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012798 // If it's packed, check also if it fits a char or a short.
12799 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012800 BestType = Context.UnsignedCharTy;
12801 BestPromotionType = Context.IntTy;
12802 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012803 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012804 BestType = Context.UnsignedShortTy;
12805 BestPromotionType = Context.IntTy;
12806 BestWidth = ShortWidth;
12807 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012808 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012809 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012810 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012811 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012812 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012813 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012814 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000012815 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012816 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012817 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012818 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000012819 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012820 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012821 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000012822 "How could an initializer get larger than ULL?");
12823 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012824 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012825 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012826 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000012827 }
12828 }
Mike Stump1eb44332009-09-09 15:08:12 +000012829
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012830 // Loop over all of the enumerator constants, changing their types to match
12831 // the type of the enum if needed.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012832 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +000012833 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012834 if (!ECD) continue; // Already issued a diagnostic.
12835
12836 // Standard C says the enumerators have int type, but we allow, as an
12837 // extension, the enumerators to be larger than int size. If each
12838 // enumerator value fits in an int, type it as an int, otherwise type it the
12839 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12840 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012841
12842 // Determine whether the value fits into an int.
12843 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012844
12845 // If it fits into an integer type, force it. Otherwise force it to match
12846 // the enum decl type.
12847 QualType NewTy;
12848 unsigned NewWidth;
12849 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000012850 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000012851 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012852 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012853 NewTy = Context.IntTy;
12854 NewWidth = IntWidth;
12855 NewSign = true;
12856 } else if (ECD->getType() == BestType) {
12857 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000012858 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012859 // C++ [dcl.enum]p4: Following the closing brace of an
12860 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012861 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012862 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012863 continue;
12864 } else {
12865 NewTy = BestType;
12866 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000012867 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012868 }
12869
12870 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000012871 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012872 InitVal.setIsSigned(NewSign);
12873 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000012874
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012875 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000012876 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000012877 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000012878 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000012879 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000012880 ECD->getInitExpr(),
12881 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000012882 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000012883 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012884 // C++ [dcl.enum]p4: Following the closing brace of an
12885 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012886 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012887 ECD->setType(EnumType);
12888 else
12889 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012890 }
Mike Stump1eb44332009-09-09 15:08:12 +000012891
John McCall1b5a6182010-05-06 08:49:23 +000012892 Enum->completeDefinition(BestType, BestPromotionType,
12893 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000012894
12895 // If we're declaring a function, ensure this decl isn't forgotten about -
12896 // it needs to go into the function scope.
12897 if (InFunctionDeclarator)
12898 DeclsInPrototypeScope.push_back(Enum);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012899
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012900 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smithbe507b62013-02-01 08:12:08 +000012901
12902 // Now that the enum type is defined, ensure it's not been underaligned.
12903 if (Enum->hasAttrs())
12904 CheckAlignasUnderalignment(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +000012905}
12906
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012907Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12908 SourceLocation StartLoc,
12909 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000012910 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000012911
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000012912 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012913 AsmString, StartLoc,
12914 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012915 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000012916 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000012917}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012918
Douglas Gregor5948ae12012-01-03 18:04:46 +000012919DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12920 SourceLocation ImportLoc,
12921 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000012922 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000012923 Module::AllVisible,
12924 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000012925 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012926 return true;
12927
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012928 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregor15de72c2011-12-02 23:23:56 +000012929 Module *ModCheck = Mod;
12930 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12931 // If we've run out of module parents, just drop the remaining identifiers.
12932 // We need the length to be consistent.
12933 if (!ModCheck)
12934 break;
12935 ModCheck = ModCheck->Parent;
12936
12937 IdentifierLocs.push_back(Path[I].second);
12938 }
12939
12940 ImportDecl *Import = ImportDecl::Create(Context,
12941 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000012942 AtLoc.isValid()? AtLoc : ImportLoc,
12943 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000012944 Context.getTranslationUnitDecl()->addDecl(Import);
12945 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012946}
12947
Richard Smith26297f52013-11-15 04:24:58 +000012948void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
12949 // FIXME: Should we synthesize an ImportDecl here?
12950 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
12951 /*Complain=*/true);
12952}
12953
Douglas Gregorca2ab452013-01-12 01:29:50 +000012954void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12955 // Create the implicit import declaration.
12956 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12957 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12958 Loc, Mod, Loc);
12959 TU->addDecl(ImportD);
12960 Consumer.HandleImplicitImportDecl(ImportD);
12961
12962 // Make the module visible.
Douglas Gregor906d66a2013-03-20 21:10:35 +000012963 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12964 /*Complain=*/false);
Douglas Gregorca2ab452013-01-12 01:29:50 +000012965}
12966
David Chisnall5f3c1632012-02-18 16:12:34 +000012967void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12968 IdentifierInfo* AliasName,
12969 SourceLocation PragmaLoc,
12970 SourceLocation NameLoc,
12971 SourceLocation AliasNameLoc) {
12972 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12973 LookupOrdinaryName);
12974 AsmLabelAttr *Attr =
12975 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000012976
12977 if (PrevDecl)
12978 PrevDecl->addAttr(Attr);
12979 else
12980 (void)ExtnameUndeclaredIdentifiers.insert(
12981 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12982}
12983
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012984void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12985 SourceLocation PragmaLoc,
12986 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012987 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012988
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012989 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000012990 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000012991 } else {
12992 (void)WeakUndeclaredIdentifiers.insert(
12993 std::pair<IdentifierInfo*,WeakInfo>
12994 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012995 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012996}
12997
12998void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12999 IdentifierInfo* AliasName,
13000 SourceLocation PragmaLoc,
13001 SourceLocation NameLoc,
13002 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000013003 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13004 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000013005 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000013006
Eli Friedmanc49f19b2009-06-05 02:44:36 +000013007 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000013008 if (!PrevDecl->hasAttr<AliasAttr>())
13009 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000013010 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000013011 } else {
13012 (void)WeakUndeclaredIdentifiers.insert(
13013 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000013014 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000013015}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000013016
13017Decl *Sema::getObjCDeclContext() const {
13018 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13019}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000013020
13021AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000013022 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000013023 return D->getAvailability();
13024}