blob: 0527e4957913aa23c46dac1f5a814fae3ccdfb1a [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 }
David Majnemerd2b0cf32013-10-20 05:40:29 +00006875
6876 // C++11 [replacement.functions]p3:
6877 // The program's definitions shall not be specified as inline.
David Majnemer3abf5f62013-10-21 00:25:32 +00006878 //
6879 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
David Majnemerd2b0cf32013-10-20 05:40:29 +00006880 if (isInline && NewFD->isReplaceableGlobalAllocationFunction())
6881 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith5f900e82013-11-16 00:47:38 +00006882 diag::ext_operator_new_delete_declared_inline)
David Majnemerd2b0cf32013-10-20 05:40:29 +00006883 << NewFD->getDeclName();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00006884 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006885
6886 // Filter out previous declarations that don't match the scope.
Richard Smitha41c97a2013-09-20 01:15:31 +00006887 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006888 isExplicitSpecialization ||
6889 isFunctionTemplateSpecialization);
Richard Smithdd9459f2013-08-13 18:18:50 +00006890
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006891 // Handle GNU asm-label extension (encoded as an attribute).
6892 if (Expr *E = (Expr*) D.getAsmLabel()) {
6893 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00006894 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00006895 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6896 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00006897 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6898 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6899 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6900 if (I != ExtnameUndeclaredIdentifiers.end()) {
6901 NewFD->addAttr(I->second);
6902 ExtnameUndeclaredIdentifiers.erase(I);
6903 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006904 }
6905
Chris Lattner2dbd2852009-04-25 06:12:16 +00006906 // Copy the parameter declarations from the declarator D to the function
6907 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006908 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00006909 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006910 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006911
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006912 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6913 // function that takes no arguments, not a function that takes a
6914 // single void argument.
6915 // We let through "const void" here because Sema::GetTypeForDeclarator
6916 // already checks for that case.
6917 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6918 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006919 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00006920 // Empty arg list, don't push any params.
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006921 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006922 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006923 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00006924 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006925 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6926 Param->setDeclContext(NewFD);
6927 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00006928
6929 if (Param->isInvalidDecl())
6930 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006931 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006932 }
Mike Stump1eb44332009-09-09 15:08:12 +00006933
John McCall183700f2009-09-21 23:43:11 +00006934 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00006935 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006936 // following example, we'll need to synthesize (unnamed)
6937 // parameters for use in the declaration.
6938 //
6939 // @code
6940 // typedef void fn(int);
6941 // fn f;
6942 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00006943
Chris Lattner1ad9b282009-04-25 06:03:53 +00006944 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00006945 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6946 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00006947 ParmVarDecl *Param =
6948 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00006949 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00006950 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006951 }
Chris Lattner84bb9442009-04-25 18:38:18 +00006952 } else {
6953 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6954 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006955 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00006956
Chris Lattner2dbd2852009-04-25 06:12:16 +00006957 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00006958 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00006959
James Molloy16f1f712012-02-29 10:24:19 +00006960 // Find all anonymous symbols defined during the declaration of this function
6961 // and add to NewFD. This lets us track decls such 'enum Y' in:
6962 //
6963 // void f(enum Y {AA} x) {}
6964 //
6965 // which would otherwise incorrectly end up in the translation unit scope.
6966 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6967 DeclsInPrototypeScope.clear();
6968
Richard Smith7586a6e2013-01-30 05:45:05 +00006969 if (D.getDeclSpec().isNoreturnSpecified())
6970 NewFD->addAttr(
6971 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6972 Context));
6973
Richard Smithb03a9df2012-03-13 05:56:40 +00006974 // Functions returning a variably modified type violate C99 6.7.5.2p2
6975 // because all functions have linkage.
6976 if (!NewFD->isInvalidDecl() &&
6977 NewFD->getResultType()->isVariablyModifiedType()) {
6978 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6979 NewFD->setInvalidDecl();
6980 }
6981
Rafael Espindola98ae8342012-05-10 02:50:16 +00006982 // Handle attributes.
Richard Smith4a97b8e2013-08-29 00:47:48 +00006983 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindola98ae8342012-05-10 02:50:16 +00006984
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006985 QualType RetType = NewFD->getResultType();
6986 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6987 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6988 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6989 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006990 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramera32966f2013-10-16 16:21:04 +00006991 // Attach the attribute to the new decl. Don't apply the attribute if it
6992 // returns an instance of the class (e.g. assignment operators).
6993 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006994 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6995 Context));
6996 }
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006997 }
6998
David Blaikie4e4d0842012-03-11 07:00:24 +00006999 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007000 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00007001 bool isExplicitSpecialization=false;
David Majnemerc371db62013-07-06 02:13:46 +00007002 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7003 CheckMain(NewFD, D.getDeclSpec());
7004
David Majnemere9f6f332013-09-16 22:44:20 +00007005 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7006 CheckMSVCRTEntryPoint(NewFD);
7007
David Majnemerc371db62013-07-06 02:13:46 +00007008 if (!NewFD->isInvalidDecl())
Richard Smithb03a9df2012-03-13 05:56:40 +00007009 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7010 isExplicitSpecialization));
Fariborz Jahanian37c765a2012-09-05 17:52:12 +00007011 else if (!Previous.empty())
Richard Smithdd9459f2013-08-13 18:18:50 +00007012 // Make graceful recovery from an invalid redeclaration.
7013 D.setRedeclaration(true);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007014 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007015 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7016 "previous declaration set still overloaded");
7017 } else {
7018 // If the declarator is a template-id, translate the parser's template
7019 // argument list into our AST format.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007020 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7021 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7022 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7023 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00007024 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007025 TemplateId->NumArgs);
7026 translateTemplateArguments(TemplateArgsPtr,
7027 TemplateArgs);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007028
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007029 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007030
Douglas Gregor89b9f102011-06-06 15:22:55 +00007031 if (NewFD->isInvalidDecl()) {
7032 HasExplicitTemplateArgs = false;
7033 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00007034 // Function template with explicit template arguments.
7035 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7036 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7037
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007038 HasExplicitTemplateArgs = false;
7039 } else if (!isFunctionTemplateSpecialization &&
7040 !D.getDeclSpec().isFriendSpecified()) {
7041 // We have encountered something that the user meant to be a
7042 // specialization (because it has explicitly-specified template
7043 // arguments) but that was not introduced with a "template<>" (or had
7044 // too few of them).
Larisse Voufoef4579c2013-08-06 01:03:05 +00007045 // FIXME: Differentiate between attempts for explicit instantiations
7046 // (starting with "template") and the rest.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007047 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7048 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7049 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00007050 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00007051 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007052 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00007053 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007054 // "friend void foo<>(int);" is an implicit specialization decl.
7055 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00007056 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007057 } else if (isFriend && isFunctionTemplateSpecialization) {
7058 // This combination is only possible in a recovery case; the user
7059 // wrote something like:
7060 // template <> friend void foo(int);
7061 // which we're recovering from as if the user had written:
7062 // friend void foo<>(int);
7063 // Go ahead and fake up a template id.
7064 HasExplicitTemplateArgs = true;
7065 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7066 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007067 }
John McCall29ae6e52010-10-13 05:45:15 +00007068
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007069 // If it's a friend (and only if it's a friend), it's possible
7070 // that either the specialized function type or the specialized
7071 // template is dependent, and therefore matching will fail. In
7072 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007073 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007074 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007075 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7076 TemplateSpecializationType::anyDependentTemplateArguments(
7077 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7078 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007079 assert(HasExplicitTemplateArgs &&
7080 "friend function specialization without template args");
7081 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7082 Previous))
7083 NewFD->setInvalidDecl();
7084 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007085 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00007086 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007087 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00007088 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007089 diag::ext_function_specialization_in_class :
7090 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007091 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007092 } else if (CheckFunctionTemplateSpecialization(NewFD,
7093 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7094 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007095 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00007096
7097 // C++ [dcl.stc]p1:
7098 // A storage-class-specifier shall not be specified in an explicit
7099 // specialization (14.7.3)
Richard Trieu62ab0102013-05-16 02:14:08 +00007100 FunctionTemplateSpecializationInfo *Info =
7101 NewFD->getTemplateSpecializationInfo();
7102 if (Info && SC != SC_None) {
7103 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor0f9dc862011-06-17 05:09:08 +00007104 Diag(NewFD->getLocation(),
7105 diag::err_explicit_specialization_inconsistent_storage_class)
7106 << SC
7107 << FixItHint::CreateRemoval(
7108 D.getDeclSpec().getStorageClassSpecLoc());
7109
7110 else
7111 Diag(NewFD->getLocation(),
7112 diag::ext_explicit_specialization_storage_class)
7113 << FixItHint::CreateRemoval(
7114 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00007115 }
7116
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007117 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7118 if (CheckMemberSpecialization(NewFD, Previous))
7119 NewFD->setInvalidDecl();
7120 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007121
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007122 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00007123 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemerc371db62013-07-06 02:13:46 +00007124 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7125 CheckMain(NewFD, D.getDeclSpec());
7126
David Majnemere9f6f332013-09-16 22:44:20 +00007127 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7128 CheckMSVCRTEntryPoint(NewFD);
7129
David Blaikie14068e82011-09-08 06:33:04 +00007130 if (NewFD->isInvalidDecl()) {
7131 // If this is a class member, mark the class invalid immediately.
7132 // This avoids some consistency errors later.
7133 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7134 methodDecl->getParent()->setInvalidDecl();
David Majnemerc371db62013-07-06 02:13:46 +00007135 } else
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007136 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7137 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00007138 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007139
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007140 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007141 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7142 "previous declaration set still overloaded");
7143
7144 NamedDecl *PrincipalDecl = (FunctionTemplate
7145 ? cast<NamedDecl>(FunctionTemplate)
7146 : NewFD);
7147
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007148 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007149 AccessSpecifier Access = AS_public;
7150 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00007151 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007152
7153 NewFD->setAccess(Access);
7154 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007155 }
7156
7157 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7158 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7159 PrincipalDecl->setNonMemberOperator();
7160
7161 // If we have a function template, check the template parameter
7162 // list. This will check and merge default template arguments.
7163 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00007164 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00007165 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007166 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00007167 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00007168 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007169 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00007170 ? TPC_FriendFunctionTemplateDefinition
7171 : TPC_FriendFunctionTemplate)
7172 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00007173 DC && DC->isRecord() &&
7174 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00007175 ? TPC_ClassTemplateMember
7176 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007177 }
7178
7179 if (NewFD->isInvalidDecl()) {
7180 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007181 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00007182 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007183 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007184 // Fake up an access specifier if it's supposed to be a class member.
7185 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7186 NewFD->setAccess(AS_public);
7187
7188 // Qualified decls generally require a previous declaration.
7189 if (D.getCXXScopeSpec().isSet()) {
7190 // ...with the major exception of templated-scope or
7191 // dependent-scope friend declarations.
7192
7193 // TODO: we currently also suppress this check in dependent
7194 // contexts because (1) the parameter depth will be off when
7195 // matching friend templates and (2) we might actually be
7196 // selecting a friend based on a dependent factor. But there
7197 // are situations where these conditions don't apply and we
7198 // can actually do this check immediately.
7199 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007200 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007201 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7202 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007203 // ignore these
7204 } else {
7205 // The user tried to provide an out-of-line definition for a
7206 // function that is a member of a class or namespace, but there
7207 // was no such member function declared (C++ [class.mfct]p2,
7208 // C++ [namespace.memdef]p2). For example:
7209 //
7210 // class X {
7211 // void f() const;
7212 // };
7213 //
7214 // void X::f() { } // ill-formed
7215 //
7216 // Complain about this problem, and attempt to suggest close
7217 // matches (e.g., those that differ only in cv-qualifiers and
7218 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007219
Richard Smith4e9686b2013-08-09 04:35:01 +00007220 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7221 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007222 AddToScope = ExtraArgs.AddToScope;
7223 return Result;
7224 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007225 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007226
7227 // Unqualified local friend declarations are required to resolve
7228 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007229 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith4e9686b2013-08-09 04:35:01 +00007230 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7231 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007232 AddToScope = ExtraArgs.AddToScope;
7233 return Result;
7234 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007235 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007236
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007237 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007238 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00007239 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007240 // An out-of-line member function declaration must also be a
7241 // definition (C++ [dcl.meaning]p1).
7242 // Note that this is not the case for explicit specializations of
7243 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00007244 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7245 // extension for compatibility with old SWIG code which likes to
7246 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007247 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7248 << D.getCXXScopeSpec().getRange();
7249 }
7250 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00007251
Rafael Espindola65611bf2013-03-02 21:41:48 +00007252 ProcessPragmaWeak(S, NewFD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00007253 checkAttributesAfterMerging(*this, *NewFD);
7254
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007255 AddKnownFunctionAttributes(NewFD);
7256
Douglas Gregord9455382010-08-06 13:50:58 +00007257 if (NewFD->hasAttr<OverloadableAttr>() &&
7258 !NewFD->getType()->getAs<FunctionProtoType>()) {
7259 Diag(NewFD->getLocation(),
7260 diag::err_attribute_overloadable_no_prototype)
7261 << NewFD;
7262
7263 // Turn this into a variadic function with no parameters.
7264 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckneref072032013-08-27 23:08:25 +00007265 FunctionProtoType::ExtProtoInfo EPI(
7266 Context.getDefaultCallingConvention(true, false));
John McCalle23cf432010-12-14 08:05:40 +00007267 EPI.Variadic = true;
7268 EPI.ExtInfo = FT->getExtInfo();
7269
Dmitri Gribenko55431692013-05-05 00:41:58 +00007270 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00007271 NewFD->setType(R);
7272 }
7273
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007274 // If there's a #pragma GCC visibility in scope, and this isn't a class
7275 // member, set the visibility of this function.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007276 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007277 AddPushedVisibilityAttribute(NewFD);
7278
John McCall8dfac0b2011-09-30 05:12:12 +00007279 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7280 // marking the function.
7281 AddCFAuditedAttribute(NewFD);
7282
Richard Smithaa4bc182013-06-30 09:48:50 +00007283 // If this is the first declaration of an extern C variable, update
7284 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00007285 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00007286 isIncompleteDeclExternC(*this, NewFD))
Richard Smith662f41b2013-06-18 20:15:12 +00007287 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007288
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007289 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007290 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007291
David Blaikie4e4d0842012-03-11 07:00:24 +00007292 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007293 if (FunctionTemplate) {
7294 if (NewFD->isInvalidDecl())
7295 FunctionTemplate->setInvalidDecl();
7296 return FunctionTemplate;
7297 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007298 }
Mike Stump1eb44332009-09-09 15:08:12 +00007299
Guy Benyeie6b9d802013-01-20 12:31:11 +00007300 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyeie6b9d802013-01-20 12:31:11 +00007301 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7302 if ((getLangOpts().OpenCLVersion >= 120)
7303 && (SC == SC_Static)) {
7304 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7305 D.setInvalidType();
7306 }
Tanya Lattner7564bcc2013-01-30 19:48:52 +00007307
7308 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7309 if (!NewFD->getResultType()->isVoidType()) {
7310 Diag(D.getIdentifierLoc(),
7311 diag::err_expected_kernel_void_return_type);
7312 D.setInvalidType();
7313 }
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007314
7315 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007316 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7317 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly98f988d2013-01-29 10:54:06 +00007318 ParmVarDecl *Param = *PI;
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007319 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyeie6b9d802013-01-20 12:31:11 +00007320 }
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00007321 }
7322
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00007323 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007324
David Blaikie4e4d0842012-03-11 07:00:24 +00007325 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007326 if (IdentifierInfo *II = NewFD->getIdentifier())
7327 if (!NewFD->isInvalidDecl() &&
7328 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7329 if (II->isStr("cudaConfigureCall")) {
7330 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7331 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7332
7333 Context.setcudaConfigureCallDecl(NewFD);
7334 }
7335 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007336
7337 // Here we have an function template explicit specialization at class scope.
7338 // The actually specialization will be postponed to template instatiation
7339 // time via the ClassScopeFunctionSpecializationDecl node.
7340 if (isDependentClassScopeExplicitSpecialization) {
7341 ClassScopeFunctionSpecializationDecl *NewSpec =
7342 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber6b020092012-06-25 17:21:05 +00007343 Context, CurContext, SourceLocation(),
7344 cast<CXXMethodDecl>(NewFD),
7345 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007346 CurContext->addDecl(NewSpec);
7347 AddToScope = false;
7348 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007349
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007350 return NewFD;
7351}
7352
7353/// \brief Perform semantic checking of a new function declaration.
7354///
7355/// Performs semantic analysis of the new function declaration
7356/// NewFD. This routine performs all semantic checking that does not
7357/// require the actual declarator involved in the declaration, and is
7358/// used both for the declaration of functions as they are parsed
7359/// (called via ActOnDeclarator) and for the declaration of functions
7360/// that have been instantiated via C++ template instantiation (called
7361/// via InstantiateDecl).
7362///
James Dennettefce31f2012-06-22 08:10:18 +00007363/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorfd056bc2009-10-13 16:30:37 +00007364/// an explicit specialization of the previous declaration.
7365///
Chris Lattnereaaebc72009-04-25 08:06:05 +00007366/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007367///
James Dennettefce31f2012-06-22 08:10:18 +00007368/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007369bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00007370 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007371 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00007372 assert(!NewFD->getResultType()->isVariablyModifiedType()
7373 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00007374
Richard Smithdd9459f2013-08-13 18:18:50 +00007375 // Determine whether the type of this function should be merged with
7376 // a previous visible declaration. This never happens for functions in C++,
7377 // and always happens in C if the previous declaration was visible.
7378 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7379 !Previous.isShadowed();
7380
Douglas Gregor7dc80e12013-01-09 00:47:56 +00007381 // Filter out any non-conflicting previous declarations.
7382 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7383
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007384 bool Redeclaration = false;
Richard Smith21c8fa82013-01-14 05:37:29 +00007385 NamedDecl *OldDecl = 0;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007386
Douglas Gregor04495c82009-02-24 01:23:02 +00007387 // Merge or overload the declaration with an existing declaration of
7388 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00007389 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00007390 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007391 // a declaration that requires merging. If it's an overload,
7392 // there's no more work to do here; we'll just add the new
7393 // function to the scope.
John McCall871b2e72009-12-09 03:35:25 +00007394 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola90cc3902013-04-15 12:49:13 +00007395 NamedDecl *Candidate = Previous.getFoundDecl();
7396 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7397 Redeclaration = true;
7398 OldDecl = Candidate;
7399 }
John McCall871b2e72009-12-09 03:35:25 +00007400 } else {
John McCallad00b772010-06-16 08:42:20 +00007401 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7402 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00007403 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007404 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00007405 break;
7406
7407 case Ovl_NonFunction:
7408 Redeclaration = true;
7409 break;
7410
7411 case Ovl_Overload:
7412 Redeclaration = false;
7413 break;
John McCall68263142009-11-18 22:49:29 +00007414 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00007415
David Blaikie4e4d0842012-03-11 07:00:24 +00007416 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00007417 // If a function name is overloadable in C, then every function
7418 // with that name must be marked "overloadable".
7419 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7420 << Redeclaration << NewFD;
7421 NamedDecl *OverloadedDecl = 0;
7422 if (Redeclaration)
7423 OverloadedDecl = OldDecl;
7424 else if (!Previous.empty())
7425 OverloadedDecl = Previous.getRepresentativeDecl();
7426 if (OverloadedDecl)
7427 Diag(OverloadedDecl->getLocation(),
7428 diag::note_attribute_overloadable_prev_overload);
7429 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7430 Context));
7431 }
John McCall68263142009-11-18 22:49:29 +00007432 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007433 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007434
Richard Smithaa4bc182013-06-30 09:48:50 +00007435 // Check for a previous extern "C" declaration with this name.
7436 if (!Redeclaration &&
7437 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7438 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7439 if (!Previous.empty()) {
7440 // This is an extern "C" declaration with the same name as a previous
7441 // declaration, and thus redeclares that entity...
7442 Redeclaration = true;
7443 OldDecl = Previous.getFoundDecl();
Richard Smithdd9459f2013-08-13 18:18:50 +00007444 MergeTypeWithPrevious = false;
Richard Smithaa4bc182013-06-30 09:48:50 +00007445
7446 // ... except in the presence of __attribute__((overloadable)).
7447 if (OldDecl->hasAttr<OverloadableAttr>()) {
7448 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7449 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7450 << Redeclaration << NewFD;
7451 Diag(Previous.getFoundDecl()->getLocation(),
7452 diag::note_attribute_overloadable_prev_overload);
7453 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7454 Context));
7455 }
7456 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7457 Redeclaration = false;
7458 OldDecl = 0;
7459 }
7460 }
7461 }
7462 }
7463
Richard Smith21c8fa82013-01-14 05:37:29 +00007464 // C++11 [dcl.constexpr]p8:
7465 // A constexpr specifier for a non-static member function that is not
7466 // a constructor declares that member function to be const.
7467 //
7468 // This needs to be delayed until we know whether this is an out-of-line
7469 // definition of a static member function.
Richard Smith84046262013-04-21 01:08:50 +00007470 //
7471 // This rule is not present in C++1y, so we produce a backwards
7472 // compatibility warning whenever it happens in C++11.
Richard Smith21c8fa82013-01-14 05:37:29 +00007473 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith84046262013-04-21 01:08:50 +00007474 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7475 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith21c8fa82013-01-14 05:37:29 +00007476 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7477 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7478 if (FunctionTemplateDecl *OldTD =
7479 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7480 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7481 if (!OldMD || !OldMD->isStatic()) {
7482 const FunctionProtoType *FPT =
7483 MD->getType()->castAs<FunctionProtoType>();
7484 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7485 EPI.TypeQuals |= Qualifiers::Const;
7486 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00007487 FPT->getArgTypes(), EPI));
Richard Smith84046262013-04-21 01:08:50 +00007488
7489 // Warn that we did this, if we're not performing template instantiation.
7490 // In that case, we'll have warned already when the template was defined.
7491 if (ActiveTemplateInstantiations.empty()) {
7492 SourceLocation AddConstLoc;
7493 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7494 .IgnoreParens().getAs<FunctionTypeLoc>())
7495 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7496
7497 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7498 << FixItHint::CreateInsertion(AddConstLoc, " const");
7499 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007500 }
7501 }
7502
7503 if (Redeclaration) {
7504 // NewFD and OldDecl represent declarations that need to be
7505 // merged.
Richard Smithdd9459f2013-08-13 18:18:50 +00007506 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith21c8fa82013-01-14 05:37:29 +00007507 NewFD->setInvalidDecl();
7508 return Redeclaration;
7509 }
7510
7511 Previous.clear();
7512 Previous.addDecl(OldDecl);
7513
7514 if (FunctionTemplateDecl *OldTemplateDecl
7515 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7516 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7517 FunctionTemplateDecl *NewTemplateDecl
7518 = NewFD->getDescribedFunctionTemplate();
7519 assert(NewTemplateDecl && "Template/non-template mismatch");
7520 if (CXXMethodDecl *Method
7521 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7522 Method->setAccess(OldTemplateDecl->getAccess());
7523 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007524 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007525
7526 // If this is an explicit specialization of a member that is a function
7527 // template, mark it as a member specialization.
7528 if (IsExplicitSpecialization &&
7529 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7530 NewTemplateDecl->setMemberSpecialization();
7531 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00007532 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007533
7534 } else {
John McCalld5617ee2013-01-25 22:31:03 +00007535 // This needs to happen first so that 'inline' propagates.
Richard Smith21c8fa82013-01-14 05:37:29 +00007536 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCalld5617ee2013-01-25 22:31:03 +00007537
7538 if (isa<CXXMethodDecl>(NewFD)) {
7539 // A valid redeclaration of a C++ method must be out-of-line,
7540 // but (unfortunately) it's not necessarily a definition
7541 // because of templates, which means that the previous
7542 // declaration is not necessarily from the class definition.
7543
7544 // For just setting the access, that doesn't matter.
7545 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7546 NewFD->setAccess(oldMethod->getAccess());
7547
7548 // Update the key-function state if necessary for this ABI.
7549 if (NewFD->isInlined() &&
7550 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7551 // setNonKeyFunction needs to work with the original
7552 // declaration from the class definition, and isVirtual() is
7553 // just faster in that case, so map back to that now.
Rafael Espindolabc650912013-10-17 15:37:26 +00007554 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCalld5617ee2013-01-25 22:31:03 +00007555 if (oldMethod->isVirtual()) {
7556 Context.setNonKeyFunction(oldMethod);
7557 }
7558 }
7559 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007560 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00007561 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007562
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007563 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00007564 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007565 // C++-specific checks.
7566 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7567 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00007568 } else if (CXXDestructorDecl *Destructor =
7569 dyn_cast<CXXDestructorDecl>(NewFD)) {
7570 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007571 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00007572
Douglas Gregor4923aa22010-07-02 20:37:36 +00007573 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00007574 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007575 if (!ClassType->isDependentType()) {
7576 DeclarationName Name
7577 = Context.DeclarationNames.getCXXDestructorName(
7578 Context.getCanonicalType(ClassType));
7579 if (NewFD->getDeclName() != Name) {
7580 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007581 NewFD->setInvalidDecl();
7582 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007583 }
7584 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007585 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00007586 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007587 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00007588 }
7589
7590 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00007591 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7592 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00007593 !Method->getDescribedFunctionTemplate() &&
7594 Method->isCanonicalDecl()) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007595 if (AddOverriddenMethods(Method->getParent(), Method)) {
7596 // If the function was marked as "static", we have a problem.
7597 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie5708c182012-10-17 00:47:58 +00007598 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007599 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00007600 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007601 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007602
7603 if (Method->isStatic())
7604 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00007605 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007606
7607 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7608 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007609 CheckOverloadedOperatorDeclaration(NewFD)) {
7610 NewFD->setInvalidDecl();
7611 return Redeclaration;
7612 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007613
7614 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7615 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007616 CheckLiteralOperatorDeclaration(NewFD)) {
7617 NewFD->setInvalidDecl();
7618 return Redeclaration;
7619 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007620
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007621 // In C++, check default arguments now that we have merged decls. Unless
7622 // the lexical context is the class, because in this case this is done
7623 // during delayed parsing anyway.
7624 if (!CurContext->isRecord())
7625 CheckCXXDefaultArguments(NewFD);
Warren Hunt2d023ec2013-11-01 23:46:51 +00007626
Douglas Gregorb68e3992010-12-21 19:47:46 +00007627 // If this function declares a builtin function, check the type of this
7628 // declaration against the expected type for the builtin.
7629 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7630 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanian9ef15182013-01-05 21:54:55 +00007631 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregorb68e3992010-12-21 19:47:46 +00007632 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7633 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7634 // The type of this function differs from the type of the builtin,
7635 // so forget about the builtin entirely.
7636 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7637 }
7638 }
Warren Hunt2d023ec2013-11-01 23:46:51 +00007639
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007640 // If this function is declared as being extern "C", then check to see if
7641 // the function returns a UDT (class, struct, or union type) that is not C
7642 // compatible, and if it does, warn the user.
Fariborz Jahanian96db3292013-03-14 23:09:00 +00007643 // But, issue any diagnostic on the first declaration only.
7644 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007645 QualType R = NewFD->getResultType();
Hans Wennborg168c07b2012-07-24 17:59:41 +00007646 if (R->isIncompleteType() && !R->isVoidType())
7647 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7648 << NewFD << R;
Douglas Gregorb38b4912012-08-07 06:14:34 +00007649 else if (!R.isPODType(Context) && !R->isVoidType() &&
7650 !R->isObjCObjectPointerType())
Hans Wennborg168c07b2012-07-24 17:59:41 +00007651 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007652 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007653 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007654 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007655}
7656
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007657static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7658 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7659 if (!TSI)
7660 return SourceRange();
7661
7662 TypeLoc TL = TSI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00007663 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007664 if (!FunctionTL)
7665 return SourceRange();
7666
David Blaikie39e6ab42013-02-18 22:06:02 +00007667 TypeLoc ResultTL = FunctionTL.getResultLoc();
7668 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007669 return ResultTL.getSourceRange();
7670
7671 return SourceRange();
7672}
7673
David Blaikie14068e82011-09-08 06:33:04 +00007674void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00007675 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7676 // static or constexpr is ill-formed.
Richard Smithde03c152013-01-17 22:16:11 +00007677 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7678 // appear in a declaration of main.
John McCall13591ed2009-07-25 04:36:53 +00007679 // static main is not an error under C99, but we should warn about it.
Richard Smithde03c152013-01-17 22:16:11 +00007680 // We accept _Noreturn main as an extension.
David Blaikie14068e82011-09-08 06:33:04 +00007681 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00007682 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00007683 ? diag::err_static_main : diag::warn_static_main)
7684 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7685 if (FD->isInlineSpecified())
7686 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7687 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko445743d2013-01-21 11:25:03 +00007688 if (DS.isNoreturnSpecified()) {
7689 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7690 SourceRange NoreturnRange(NoreturnLoc,
7691 PP.getLocForEndOfToken(NoreturnLoc));
7692 Diag(NoreturnLoc, diag::ext_noreturn_main);
7693 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7694 << FixItHint::CreateRemoval(NoreturnRange);
7695 }
Richard Smitha5065862012-02-04 06:10:17 +00007696 if (FD->isConstexpr()) {
7697 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7698 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7699 FD->setConstexpr(false);
7700 }
John McCall13591ed2009-07-25 04:36:53 +00007701
Joey Goulyc879fe52013-11-05 12:30:39 +00007702 if (getLangOpts().OpenCL) {
7703 Diag(FD->getLocation(), diag::err_opencl_no_main)
7704 << FD->hasAttr<OpenCLKernelAttr>();
7705 FD->setInvalidDecl();
7706 return;
7707 }
7708
John McCall13591ed2009-07-25 04:36:53 +00007709 QualType T = FD->getType();
7710 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00007711 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007712
John McCall75d8ba32012-02-14 19:50:52 +00007713 // All the standards say that main() should should return 'int'.
7714 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7715 // In C and C++, main magically returns 0 if you fall off the end;
7716 // set the flag which tells us that.
7717 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7718 FD->setHasImplicitReturnZero(true);
7719
7720 // In C with GNU extensions we allow main() to have non-integer return
7721 // type, but we should warn about the extension, and we disable the
7722 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00007723 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00007724 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7725
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007726 SourceRange ResultRange = getResultSourceRange(FD);
7727 if (ResultRange.isValid())
7728 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7729 << FixItHint::CreateReplacement(ResultRange, "int");
7730
John McCall75d8ba32012-02-14 19:50:52 +00007731 // Otherwise, this is just a flat-out error.
7732 } else {
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007733 SourceRange ResultRange = getResultSourceRange(FD);
7734 if (ResultRange.isValid())
7735 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7736 << FixItHint::CreateReplacement(ResultRange, "int");
7737 else
7738 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7739
John McCall13591ed2009-07-25 04:36:53 +00007740 FD->setInvalidDecl(true);
7741 }
7742
7743 // Treat protoless main() as nullary.
7744 if (isa<FunctionNoProtoType>(FT)) return;
7745
7746 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7747 unsigned nparams = FTP->getNumArgs();
7748 assert(FD->getNumParams() == nparams);
7749
John McCall66755862009-12-24 09:58:38 +00007750 bool HasExtraParameters = (nparams > 3);
7751
7752 // Darwin passes an undocumented fourth argument of type char**. If
7753 // other platforms start sprouting these, the logic below will start
7754 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007755 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00007756 HasExtraParameters = false;
7757
7758 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00007759 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7760 FD->setInvalidDecl(true);
7761 nparams = 3;
7762 }
7763
7764 // FIXME: a lot of the following diagnostics would be improved
7765 // if we had some location information about types.
7766
7767 QualType CharPP =
7768 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00007769 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00007770
7771 for (unsigned i = 0; i < nparams; ++i) {
7772 QualType AT = FTP->getArgType(i);
7773
7774 bool mismatch = true;
7775
7776 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7777 mismatch = false;
7778 else if (Expected[i] == CharPP) {
7779 // As an extension, the following forms are okay:
7780 // char const **
7781 // char const * const *
7782 // char * const *
7783
John McCall0953e762009-09-24 19:53:00 +00007784 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00007785 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00007786 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7787 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith485b3122013-01-29 02:49:47 +00007788 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7789 Context.CharTy)) {
John McCall13591ed2009-07-25 04:36:53 +00007790 qs.removeConst();
7791 mismatch = !qs.empty();
7792 }
7793 }
7794
7795 if (mismatch) {
7796 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7797 // TODO: suggest replacing given type with expected type
7798 FD->setInvalidDecl(true);
7799 }
7800 }
7801
7802 if (nparams == 1 && !FD->isInvalidDecl()) {
7803 Diag(FD->getLocation(), diag::warn_main_one_arg);
7804 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007805
7806 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemere9f6f332013-09-16 22:44:20 +00007807 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7808 FD->setInvalidDecl();
7809 }
7810}
7811
7812void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7813 QualType T = FD->getType();
7814 assert(T->isFunctionType() && "function decl is not of function type");
7815 const FunctionType *FT = T->castAs<FunctionType>();
7816
7817 // Set an implicit return of 'zero' if the function can return some integral,
7818 // enumeration, pointer or nullptr type.
7819 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7820 FT->getResultType()->isAnyPointerType() ||
7821 FT->getResultType()->isNullPtrType())
7822 // DllMain is exempt because a return value of zero means it failed.
7823 if (FD->getName() != "DllMain")
7824 FD->setHasImplicitReturnZero(true);
7825
7826 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7827 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007828 FD->setInvalidDecl();
7829 }
John McCall8c4859a2009-07-24 03:03:21 +00007830}
7831
Eli Friedmanc594b322008-05-20 13:48:25 +00007832bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007833 // FIXME: Need strict checking. In C89, we need to check for
7834 // any assignment, increment, decrement, function-calls, or
7835 // commas outside of a sizeof. In C99, it's the same list,
7836 // except that the aforementioned are allowed in unevaluated
7837 // expressions. Everything else falls under the
7838 // "may accept other forms of constant expressions" exception.
7839 // (We never end up here for C++, so the constant expression
7840 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00007841 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00007842 return false;
Eli Friedman21298282009-02-26 04:47:58 +00007843 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7844 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00007845 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00007846}
7847
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007848namespace {
7849 // Visits an initialization expression to see if OrigDecl is evaluated in
7850 // its own initialization and throws a warning if it does.
7851 class SelfReferenceChecker
7852 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7853 Sema &S;
7854 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00007855 bool isRecordType;
7856 bool isPODType;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007857 bool isReferenceType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007858
7859 public:
7860 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7861
7862 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00007863 S(S), OrigDecl(OrigDecl) {
7864 isPODType = false;
7865 isRecordType = false;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007866 isReferenceType = false;
Richard Trieu898267f2011-09-01 21:44:13 +00007867 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7868 isPODType = VD->getType().isPODType(S.Context);
7869 isRecordType = VD->getType()->isRecordType();
Hans Wennborg8be9e772012-08-17 10:12:33 +00007870 isReferenceType = VD->getType()->isReferenceType();
Richard Trieu898267f2011-09-01 21:44:13 +00007871 }
7872 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007873
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007874 // For most expressions, the cast is directly above the DeclRefExpr.
7875 // For conditional operators, the cast can be outside the conditional
7876 // operator if both expressions are DeclRefExpr's.
7877 void HandleValue(Expr *E) {
Richard Trieu568f7852012-10-01 17:39:51 +00007878 if (isReferenceType)
7879 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007880 E = E->IgnoreParenImpCasts();
7881 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7882 HandleDeclRefExpr(DRE);
7883 return;
7884 }
7885
7886 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7887 HandleValue(CO->getTrueExpr());
7888 HandleValue(CO->getFalseExpr());
Richard Trieu6b2cc422012-10-03 00:41:36 +00007889 return;
7890 }
7891
7892 if (isa<MemberExpr>(E)) {
7893 Expr *Base = E->IgnoreParenImpCasts();
7894 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7895 // Check for static member variables and don't warn on them.
7896 if (!isa<FieldDecl>(ME->getMemberDecl()))
7897 return;
7898 Base = ME->getBase()->IgnoreParenImpCasts();
7899 }
7900 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7901 HandleDeclRefExpr(DRE);
7902 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007903 }
7904 }
7905
Richard Trieu568f7852012-10-01 17:39:51 +00007906 // Reference types are handled here since all uses of references are
7907 // bad, not just r-value uses.
7908 void VisitDeclRefExpr(DeclRefExpr *E) {
7909 if (isReferenceType)
7910 HandleDeclRefExpr(E);
7911 }
7912
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007913 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu6b2cc422012-10-03 00:41:36 +00007914 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007915 (isRecordType && E->getCastKind() == CK_NoOp))
7916 HandleValue(E->getSubExpr());
7917
7918 Inherited::VisitImplicitCastExpr(E);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007919 }
7920
Richard Trieu898267f2011-09-01 21:44:13 +00007921 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007922 // Don't warn on arrays since they can be treated as pointers.
Richard Trieu47eb8982011-09-07 00:58:53 +00007923 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007924
Richard Trieu6b2cc422012-10-03 00:41:36 +00007925 // Warn when a non-static method call is followed by non-static member
7926 // field accesses, which is followed by a DeclRefExpr.
7927 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7928 bool Warn = (MD && !MD->isStatic());
7929 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7930 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7931 if (!isa<FieldDecl>(ME->getMemberDecl()))
7932 Warn = false;
7933 Base = ME->getBase()->IgnoreParenImpCasts();
7934 }
Richard Trieu898267f2011-09-01 21:44:13 +00007935
Richard Trieu6b2cc422012-10-03 00:41:36 +00007936 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7937 if (Warn)
7938 HandleDeclRefExpr(DRE);
7939 return;
7940 }
7941
7942 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7943 // Visit that expression.
7944 Visit(Base);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007945 }
7946
Richard Trieu8af742a2013-03-26 03:41:40 +00007947 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7948 if (E->getNumArgs() > 0)
7949 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7950 HandleDeclRefExpr(DRE);
7951
7952 Inherited::VisitCXXOperatorCallExpr(E);
7953 }
7954
Richard Trieu898267f2011-09-01 21:44:13 +00007955 void VisitUnaryOperator(UnaryOperator *E) {
7956 // For POD record types, addresses of its own members are well-defined.
Richard Trieu6b2cc422012-10-03 00:41:36 +00007957 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7958 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7959 if (!isPODType)
7960 HandleValue(E->getSubExpr());
7961 return;
7962 }
Richard Trieu898267f2011-09-01 21:44:13 +00007963 Inherited::VisitUnaryOperator(E);
Richard Smith0f2fc5f2013-05-03 19:16:22 +00007964 }
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007965
7966 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7967
Richard Trieu898267f2011-09-01 21:44:13 +00007968 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumif3052792013-01-19 01:54:35 +00007969 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007970 if (OrigDecl != ReferenceDecl) return;
Ted Kremenek39371b82013-01-19 04:33:14 +00007971 unsigned diag;
7972 if (isReferenceType) {
7973 diag = diag::warn_uninit_self_reference_in_reference_init;
7974 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7975 diag = diag::warn_static_self_reference_in_init;
7976 } else {
7977 diag = diag::warn_uninit_self_reference_in_init;
7978 }
7979
Richard Trieu898267f2011-09-01 21:44:13 +00007980 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborg5965b7c2012-08-20 08:52:22 +00007981 S.PDiag(diag)
Hans Wennborg7821e072012-09-21 08:58:33 +00007982 << DRE->getNameInfo().getName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00007983 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00007984 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007985 }
7986 };
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007987
Richard Trieu568f7852012-10-01 17:39:51 +00007988 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7989 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7990 bool DirectInit) {
7991 // Parameters arguments are occassionially constructed with itself,
7992 // for instance, in recursive functions. Skip them.
7993 if (isa<ParmVarDecl>(OrigDecl))
7994 return;
7995
7996 E = E->IgnoreParens();
7997
7998 // Skip checking T a = a where T is not a record or reference type.
7999 // Doing so is a way to silence uninitialized warnings.
8000 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8001 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8002 if (ICE->getCastKind() == CK_LValueToRValue)
8003 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8004 if (DRE->getDecl() == OrigDecl)
8005 return;
8006
8007 SelfReferenceChecker(S, OrigDecl).Visit(E);
8008 }
Richard Trieu898267f2011-09-01 21:44:13 +00008009}
8010
Douglas Gregor09f41cf2009-01-14 15:45:31 +00008011/// AddInitializerToDecl - Adds the initializer Init to the
8012/// declaration dcl. If DirectInit is true, this is C++ direct
8013/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00008014void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8015 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008016 // If there is no declaration, there was an error parsing it. Just ignore
8017 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00008018 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008019 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008020
Douglas Gregor021c3b32009-03-11 23:00:04 +00008021 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8022 // With declarators parsed the way they are, the parser cannot
8023 // distinguish between a normal initializer and a pure-specifier.
8024 // Thus this grotesque test.
8025 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00008026 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00008027 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8028 CheckPureMethod(Method, Init->getSourceRange());
8029 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00008030 Diag(Method->getLocation(), diag::err_member_function_initialization)
8031 << Method->getDeclName() << Init->getSourceRange();
8032 Method->setInvalidDecl();
8033 }
8034 return;
8035 }
8036
Steve Naroff410e3e22007-09-12 20:13:48 +00008037 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8038 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00008039 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8040 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00008041 RealDecl->setInvalidDecl();
8042 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00008043 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008044 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8045
Richard Smith01888722011-12-15 19:20:59 +00008046 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00008047 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008048 Expr *DeduceInit = Init;
8049 // Initializer could be a C++ direct-initializer. Deduction only works if it
8050 // contains exactly one expression.
8051 if (CXXDirectInit) {
8052 if (CXXDirectInit->getNumExprs() == 0) {
8053 // It isn't possible to write this directly, but it is possible to
8054 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00008055 Diag(CXXDirectInit->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008056 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8057 : diag::err_auto_var_init_no_expression)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008058 << VDecl->getDeclName() << VDecl->getType()
8059 << VDecl->getSourceRange();
8060 RealDecl->setInvalidDecl();
8061 return;
8062 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00008063 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008064 VDecl->isInitCapture()
8065 ? diag::err_init_capture_multiple_expressions
8066 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008067 << VDecl->getDeclName() << VDecl->getType()
8068 << VDecl->getSourceRange();
8069 RealDecl->setInvalidDecl();
8070 return;
8071 } else {
8072 DeduceInit = CXXDirectInit->getExpr(0);
8073 }
8074 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008075
8076 // Expressions default to 'id' when we're in a debugger.
8077 bool DefaultedToAuto = false;
8078 if (getLangOpts().DebuggerCastResultToId &&
8079 Init->getType() == Context.UnknownAnyTy) {
8080 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8081 if (Result.isInvalid()) {
8082 VDecl->setInvalidDecl();
8083 return;
8084 }
8085 Init = Result.take();
8086 DefaultedToAuto = true;
8087 }
Richard Smith9b131752013-04-30 21:23:01 +00008088
8089 QualType DeducedType;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008090 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00008091 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008092 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9b131752013-04-30 21:23:01 +00008093 if (DeducedType.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008094 RealDecl->setInvalidDecl();
8095 return;
8096 }
Richard Smith9b131752013-04-30 21:23:01 +00008097 VDecl->setType(DeducedType);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00008098 assert(VDecl->isLinkageValid());
Rafael Espindola2d9e8832013-03-12 21:06:00 +00008099
John McCallf85e1932011-06-15 23:02:42 +00008100 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00008101 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00008102 VDecl->setInvalidDecl();
8103
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008104 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8105 // 'id' instead of a specific object type prevents most of our usual checks.
8106 // We only want to warn outside of template instantiations, though:
8107 // inside a template, the 'id' could have come from a parameter.
Douglas Gregor1344e942013-03-07 22:57:58 +00008108 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith9b131752013-04-30 21:23:01 +00008109 DeducedType->isObjCIdType()) {
8110 SourceLocation Loc =
8111 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008112 Diag(Loc, diag::warn_auto_var_is_id)
8113 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8114 }
8115
Richard Smith34b41d92011-02-20 03:19:35 +00008116 // If this is a redeclaration, check that the type we just deduced matches
8117 // the previously declared type.
Richard Smithdd9459f2013-08-13 18:18:50 +00008118 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8119 // We never need to merge the type, because we cannot form an incomplete
8120 // array of auto, nor deduce such a type.
8121 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8122 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00008123
8124 // Check the deduced type is valid for a variable declaration.
8125 CheckVariableDeclarationType(VDecl);
8126 if (VDecl->isInvalidDecl())
8127 return;
Richard Smith34b41d92011-02-20 03:19:35 +00008128 }
Richard Smith01888722011-12-15 19:20:59 +00008129
8130 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8131 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8132 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8133 VDecl->setInvalidDecl();
8134 return;
8135 }
8136
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008137 if (!VDecl->getType()->isDependentType()) {
8138 // A definition must end up with a complete type, which means it must be
8139 // complete with the restriction that an array type might be completed by
8140 // the initializer; note that later code assumes this restriction.
8141 QualType BaseDeclType = VDecl->getType();
8142 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8143 BaseDeclType = Array->getElementType();
8144 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8145 diag::err_typecheck_decl_incomplete_type)) {
8146 RealDecl->setInvalidDecl();
8147 return;
8148 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008149
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008150 // The variable can not have an abstract class type.
8151 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8152 diag::err_abstract_type_in_decl,
8153 AbstractVariableType))
8154 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00008155 }
8156
Sebastian Redl31310a22010-02-01 20:16:42 +00008157 const VarDecl *Def;
8158 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00008159 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00008160 << VDecl->getDeclName();
8161 Diag(Def->getLocation(), diag::note_previous_definition);
8162 VDecl->setInvalidDecl();
8163 return;
8164 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008165
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008166 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00008167 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00008168 // C++ [class.static.data]p4
8169 // If a static data member is of const integral or const
8170 // enumeration type, its declaration in the class definition can
8171 // specify a constant-initializer which shall be an integral
8172 // constant expression (5.19). In that case, the member can appear
8173 // in integral constant expressions. The member shall still be
8174 // defined in a namespace scope if it is used in the program and the
8175 // namespace scope definition shall not contain an initializer.
8176 //
8177 // We already performed a redefinition check above, but for static
8178 // data members we also need to check whether there was an in-class
8179 // declaration with an initializer.
8180 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00008181 Diag(VDecl->getLocation(), diag::err_redefinition)
8182 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00008183 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8184 return;
8185 }
Douglas Gregor275a3692009-03-10 23:43:53 +00008186
Douglas Gregora31040f2010-12-16 01:31:22 +00008187 if (VDecl->hasLocalStorage())
8188 getCurFunction()->setHasBranchProtectedScope();
8189
8190 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8191 VDecl->setInvalidDecl();
8192 return;
8193 }
8194 }
John McCalle46f62c2010-08-01 01:24:59 +00008195
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008196 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8197 // a kernel function cannot be initialized."
8198 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8199 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8200 VDecl->setInvalidDecl();
8201 return;
8202 }
8203
Steve Naroffbb204692007-09-12 14:07:44 +00008204 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00008205 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00008206 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008207
Douglas Gregor1344e942013-03-07 22:57:58 +00008208 // Expressions default to 'id' when we're in a debugger
8209 // and we are assigning it to a variable of Objective-C pointer type.
8210 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8211 Init->getType() == Context.UnknownAnyTy) {
8212 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8213 if (Result.isInvalid()) {
8214 VDecl->setInvalidDecl();
8215 return;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008216 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008217 Init = Result.take();
8218 }
Richard Smith01888722011-12-15 19:20:59 +00008219
8220 // Perform the initialization.
8221 if (!VDecl->isInvalidDecl()) {
8222 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8223 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00008224 = DirectInit ?
8225 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8226 Init->getLocStart(),
8227 Init->getLocEnd())
8228 : InitializationKind::CreateDirectList(
8229 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00008230 : InitializationKind::CreateCopy(VDecl->getLocation(),
8231 Init->getLocStart());
8232
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008233 MultiExprArg Args = Init;
8234 if (CXXDirectInit)
8235 Args = MultiExprArg(CXXDirectInit->getExprs(),
8236 CXXDirectInit->getNumExprs());
8237
8238 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8239 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith01888722011-12-15 19:20:59 +00008240 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00008241 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00008242 return;
Steve Naroffbb204692007-09-12 14:07:44 +00008243 }
Richard Smith01888722011-12-15 19:20:59 +00008244
8245 Init = Result.takeAs<Expr>();
8246 }
8247
Richard Trieu568f7852012-10-01 17:39:51 +00008248 // Check for self-references within variable initializers.
8249 // Variables declared within a function/method body (except for references)
8250 // are handled by a dataflow analysis.
8251 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8252 VDecl->getType()->isReferenceType()) {
8253 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8254 }
8255
Richard Smith01888722011-12-15 19:20:59 +00008256 // If the type changed, it means we had an incomplete type that was
8257 // completed by the initializer. For example:
8258 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00008259 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00008260 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00008261 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00008262
Jordan Rosee10f4d32012-09-15 02:48:31 +00008263 if (!VDecl->isInvalidDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00008264 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8265
Jordan Rosee10f4d32012-09-15 02:48:31 +00008266 if (VDecl->hasAttr<BlocksAttr>())
8267 checkRetainCycles(VDecl, Init);
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008268
8269 // It is safe to assign a weak reference into a strong variable.
8270 // Although this code can still have problems:
8271 // id x = self.weakProp;
8272 // id y = self.weakProp;
8273 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8274 // paths through the function. This should be revisited if
8275 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek904a3262012-12-20 22:31:27 +00008276 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008277 DiagnosticsEngine::Level Level =
8278 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8279 Init->getLocStart());
8280 if (Level != DiagnosticsEngine::Ignored)
8281 getCurFunction()->markSafeWeakUse(Init);
8282 }
Jordan Rosee10f4d32012-09-15 02:48:31 +00008283 }
8284
Richard Smith41956372013-01-14 22:39:08 +00008285 // The initialization is usually a full-expression.
8286 //
8287 // FIXME: If this is a braced initialization of an aggregate, it is not
8288 // an expression, and each individual field initializer is a separate
8289 // full-expression. For instance, in:
8290 //
8291 // struct Temp { ~Temp(); };
8292 // struct S { S(Temp); };
8293 // struct T { S a, b; } t = { Temp(), Temp() }
8294 //
8295 // we should destroy the first Temp before constructing the second.
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008296 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8297 false,
8298 VDecl->isConstexpr());
Richard Smith41956372013-01-14 22:39:08 +00008299 if (Result.isInvalid()) {
8300 VDecl->setInvalidDecl();
8301 return;
8302 }
8303 Init = Result.take();
8304
Richard Smith01888722011-12-15 19:20:59 +00008305 // Attach the initializer to the decl.
8306 VDecl->setInit(Init);
8307
8308 if (VDecl->isLocalVarDecl()) {
8309 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8310 // static storage duration shall be constant expressions or string literals.
8311 // C++ does not have this restriction.
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008312 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8313 if (VDecl->getStorageClass() == SC_Static)
8314 CheckForConstantInitializer(Init, DclT);
8315 // C89 is stricter than C99 for non-static aggregate types.
8316 // C89 6.5.7p3: All the expressions [...] in an initializer list
8317 // for an object that has aggregate or union type shall be
8318 // constant expressions.
8319 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanella82026302013-07-22 19:10:20 +00008320 isa<InitListExpr>(Init) &&
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008321 !Init->isConstantInitializer(Context, false))
8322 Diag(Init->getExprLoc(),
8323 diag::ext_aggregate_init_not_constant)
8324 << Init->getSourceRange();
8325 }
Mike Stump1eb44332009-09-09 15:08:12 +00008326 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00008327 VDecl->getLexicalDeclContext()->isRecord()) {
8328 // This is an in-class initialization for a static data member, e.g.,
8329 //
8330 // struct S {
8331 // static const int value = 17;
8332 // };
8333
Douglas Gregor021c3b32009-03-11 23:00:04 +00008334 // C++ [class.mem]p4:
8335 // A member-declarator can contain a constant-initializer only
8336 // if it declares a static member (9.4) of const integral or
8337 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00008338 //
Richard Smith01888722011-12-15 19:20:59 +00008339 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00008340 // If a non-volatile const static data member is of integral or
8341 // enumeration type, its declaration in the class definition can
8342 // specify a brace-or-equal-initializer in which every initalizer-clause
8343 // that is an assignment-expression is a constant expression. A static
8344 // data member of literal type can be declared in the class definition
8345 // with the constexpr specifier; if so, its declaration shall specify a
8346 // brace-or-equal-initializer in which every initializer-clause that is
8347 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00008348
8349 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00008350 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00008351
Richard Smithc6d990a2011-09-29 19:11:37 +00008352 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00008353 // type. We separately check that every constexpr variable is of literal
8354 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00008355 } else if (VDecl->isConstexpr()) {
8356
John McCall4e635642010-09-10 23:21:22 +00008357 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00008358 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00008359 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8360 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008361 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008362
8363 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00008364 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00008365 // Check whether the expression is a constant expression.
8366 SourceLocation Loc;
Richard Smith80ad52f2013-01-02 11:42:31 +00008367 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00008368 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00008369 // in-class initializer cannot be volatile.
8370 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8371 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00008372 ; // Nothing to check.
8373 else if (Init->isIntegerConstantExpr(Context, &Loc))
8374 ; // Ok, it's an ICE!
8375 else if (Init->isEvaluatable(Context)) {
8376 // If we can constant fold the initializer through heroics, accept it,
8377 // but report this as a use of an extension for -pedantic.
8378 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8379 << Init->getSourceRange();
8380 } else {
8381 // Otherwise, this is some crazy unknown case. Report the issue at the
8382 // location provided by the isIntegerConstantExpr failed check.
8383 Diag(Loc, diag::err_in_class_initializer_non_constant)
8384 << Init->getSourceRange();
8385 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008386 }
8387
Richard Smith01888722011-12-15 19:20:59 +00008388 // We allow foldable floating-point constants as an extension.
8389 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithb4b1d692013-01-25 04:22:16 +00008390 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8391 // it anyway and provide a fixit to add the 'constexpr'.
8392 if (getLangOpts().CPlusPlus11) {
David Blaikiea367e9d2013-01-29 22:26:08 +00008393 Diag(VDecl->getLocation(),
8394 diag::ext_in_class_initializer_float_type_cxx11)
8395 << DclT << Init->getSourceRange();
8396 Diag(VDecl->getLocStart(),
8397 diag::note_in_class_initializer_float_type_cxx11)
8398 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithb4b1d692013-01-25 04:22:16 +00008399 } else {
8400 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8401 << DclT << Init->getSourceRange();
John McCall4e635642010-09-10 23:21:22 +00008402
Richard Smithb4b1d692013-01-25 04:22:16 +00008403 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8404 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8405 << Init->getSourceRange();
8406 VDecl->setInvalidDecl();
8407 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00008408 }
Richard Smith947be192011-09-29 23:18:34 +00008409
Richard Smith01888722011-12-15 19:20:59 +00008410 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smitha10b9782013-04-22 15:31:51 +00008411 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith947be192011-09-29 23:18:34 +00008412 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00008413 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00008414 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8415 VDecl->setConstexpr(true);
8416
Richard Smithc6d990a2011-09-29 19:11:37 +00008417 } else {
8418 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00008419 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00008420 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008421 }
Steve Naroff248a7532008-04-15 22:42:06 +00008422 } else if (VDecl->isFileVarDecl()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008423 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008424 (!getLangOpts().CPlusPlus ||
Rafael Espindola5b34b9c2013-03-29 07:56:05 +00008425 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smithd0629eb2013-09-27 20:14:12 +00008426 VDecl->isExternC())) &&
8427 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff410e3e22007-09-12 20:13:48 +00008428 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00008429
Richard Smith01888722011-12-15 19:20:59 +00008430 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00008431 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00008432 CheckForConstantInitializer(Init, DclT);
Richard Smith6a570f62013-04-14 20:11:31 +00008433 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8434 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8435 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smithb6b127f2013-04-15 08:07:34 +00008436 !Init->isConstantInitializer(
8437 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6a570f62013-04-14 20:11:31 +00008438 // GNU C++98 edits for __thread, [basic.start.init]p4:
8439 // An object of thread storage duration shall not require dynamic
8440 // initialization.
8441 // FIXME: Need strict checking here.
8442 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8443 if (getLangOpts().CPlusPlus11)
8444 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8445 }
Steve Naroffbb204692007-09-12 14:07:44 +00008446 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008447
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008448 // We will represent direct-initialization similarly to copy-initialization:
8449 // int x(1); -as-> int x = 1;
8450 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8451 //
8452 // Clients that want to distinguish between the two forms, can check for
8453 // direct initializer using VarDecl::getInitStyle().
8454 // A major benefit is that clients that don't particularly care about which
8455 // exactly form was it (like the CodeGen) can handle both cases without
8456 // special case code.
8457
8458 // C++ 8.5p11:
8459 // The form of initialization (using parentheses or '=') is generally
8460 // insignificant, but does matter when the entity being initialized has a
8461 // class type.
8462 if (CXXDirectInit) {
8463 assert(DirectInit && "Call-style initializer must be direct init.");
8464 VDecl->setInitStyle(VarDecl::CallInit);
8465 } else if (DirectInit) {
8466 // This must be list-initialization. No other way is direct-initialization.
8467 VDecl->setInitStyle(VarDecl::ListInit);
8468 }
8469
John McCall2998d6b2011-01-19 11:48:09 +00008470 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00008471}
8472
John McCall7727acf2010-03-31 02:13:20 +00008473/// ActOnInitializerError - Given that there was an error parsing an
8474/// initializer for the given declaration, try to return to some form
8475/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00008476void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00008477 // Our main concern here is re-establishing invariants like "a
8478 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00008479 if (!D || D->isInvalidDecl()) return;
8480
8481 VarDecl *VD = dyn_cast<VarDecl>(D);
8482 if (!VD) return;
8483
Richard Smith34b41d92011-02-20 03:19:35 +00008484 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00008485 if (ParsingInitForAutoVars.count(D)) {
8486 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008487 return;
8488 }
8489
John McCall7727acf2010-03-31 02:13:20 +00008490 QualType Ty = VD->getType();
8491 if (Ty->isDependentType()) return;
8492
8493 // Require a complete type.
8494 if (RequireCompleteType(VD->getLocation(),
8495 Context.getBaseElementType(Ty),
8496 diag::err_typecheck_decl_incomplete_type)) {
8497 VD->setInvalidDecl();
8498 return;
8499 }
8500
8501 // Require an abstract type.
8502 if (RequireNonAbstractType(VD->getLocation(), Ty,
8503 diag::err_abstract_type_in_decl,
8504 AbstractVariableType)) {
8505 VD->setInvalidDecl();
8506 return;
8507 }
8508
8509 // Don't bother complaining about constructors or destructors,
8510 // though.
8511}
8512
John McCalld226f652010-08-21 09:40:31 +00008513void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00008514 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00008515 // If there is no declaration, there was an error parsing it. Just ignore it.
8516 if (RealDecl == 0)
8517 return;
8518
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008519 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8520 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008521
Richard Smithdd4b3502011-12-25 21:17:58 +00008522 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00008523 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00008524 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8525 << Var->getDeclName() << Type;
8526 Var->setInvalidDecl();
8527 return;
8528 }
Mike Stump1eb44332009-09-09 15:08:12 +00008529
Richard Smithdd4b3502011-12-25 21:17:58 +00008530 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00008531 // the constexpr specifier; if so, its declaration shall specify
8532 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00008533 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8534 // the definition of a variable [...] or the declaration of a static data
8535 // member.
8536 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8537 if (Var->isStaticDataMember())
8538 Diag(Var->getLocation(),
8539 diag::err_constexpr_static_mem_var_requires_init)
8540 << Var->getDeclName();
8541 else
8542 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00008543 Var->setInvalidDecl();
8544 return;
8545 }
8546
Douglas Gregor60c93c92010-02-09 07:26:29 +00008547 switch (Var->isThisDeclarationADefinition()) {
8548 case VarDecl::Definition:
8549 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8550 break;
8551
8552 // We have an out-of-line definition of a static data member
8553 // that has an in-class initializer, so we type-check this like
8554 // a declaration.
8555 //
8556 // Fall through
8557
8558 case VarDecl::DeclarationOnly:
8559 // It's only a declaration.
8560
8561 // Block scope. C99 6.7p7: If an identifier for an object is
8562 // declared with no linkage (C99 6.2.2p6), the type for the
8563 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00008564 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008565 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00008566 RequireCompleteType(Var->getLocation(), Type,
8567 diag::err_typecheck_decl_incomplete_type))
8568 Var->setInvalidDecl();
8569
8570 // Make sure that the type is not abstract.
8571 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8572 RequireNonAbstractType(Var->getLocation(), Type,
8573 diag::err_abstract_type_in_decl,
8574 AbstractVariableType))
8575 Var->setInvalidDecl();
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008576 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008577 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008578 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008579 Diag(Var->getLocation(), diag::note_private_extern);
8580 }
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008581
Douglas Gregor60c93c92010-02-09 07:26:29 +00008582 return;
8583
8584 case VarDecl::TentativeDefinition:
8585 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8586 // object that has file scope without an initializer, and without a
8587 // storage-class specifier or with the storage-class specifier "static",
8588 // constitutes a tentative definition. Note: A tentative definition with
8589 // external linkage is valid (C99 6.2.2p5).
8590 if (!Var->isInvalidDecl()) {
8591 if (const IncompleteArrayType *ArrayT
8592 = Context.getAsIncompleteArrayType(Type)) {
8593 if (RequireCompleteType(Var->getLocation(),
8594 ArrayT->getElementType(),
8595 diag::err_illegal_decl_array_incomplete_type))
8596 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00008597 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00008598 // C99 6.9.2p3: If the declaration of an identifier for an object is
8599 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8600 // declared type shall not be an incomplete type.
8601 // NOTE: code such as the following
8602 // static struct s;
8603 // struct s { int a; };
8604 // is accepted by gcc. Hence here we issue a warning instead of
8605 // an error and we do not invalidate the static declaration.
8606 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00008607 if (Var->isFirstDecl())
Douglas Gregor60c93c92010-02-09 07:26:29 +00008608 RequireCompleteType(Var->getLocation(), Type,
8609 diag::ext_typecheck_decl_incomplete_type);
8610 }
8611 }
8612
8613 // Record the tentative definition; we're done.
8614 if (!Var->isInvalidDecl())
8615 TentativeDefinitions.push_back(Var);
8616 return;
8617 }
8618
8619 // Provide a specific diagnostic for uninitialized variable
8620 // definitions with incomplete array type.
8621 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00008622 Diag(Var->getLocation(),
8623 diag::err_typecheck_incomplete_array_needs_initializer);
8624 Var->setInvalidDecl();
8625 return;
8626 }
8627
John McCallb567a8b2010-08-01 01:25:24 +00008628 // Provide a specific diagnostic for uninitialized variable
8629 // definitions with reference type.
8630 if (Type->isReferenceType()) {
8631 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8632 << Var->getDeclName()
8633 << SourceRange(Var->getLocation(), Var->getLocation());
8634 Var->setInvalidDecl();
8635 return;
8636 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008637
8638 // Do not attempt to type-check the default initializer for a
8639 // variable with dependent type.
8640 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00008641 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00008642
Douglas Gregor60c93c92010-02-09 07:26:29 +00008643 if (Var->isInvalidDecl())
8644 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00008645
Douglas Gregor60c93c92010-02-09 07:26:29 +00008646 if (RequireCompleteType(Var->getLocation(),
8647 Context.getBaseElementType(Type),
8648 diag::err_typecheck_decl_incomplete_type)) {
8649 Var->setInvalidDecl();
8650 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008651 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008652
Douglas Gregor60c93c92010-02-09 07:26:29 +00008653 // The variable can not have an abstract class type.
8654 if (RequireNonAbstractType(Var->getLocation(), Type,
8655 diag::err_abstract_type_in_decl,
8656 AbstractVariableType)) {
8657 Var->setInvalidDecl();
8658 return;
8659 }
8660
Douglas Gregor4337dc72011-05-21 17:52:48 +00008661 // Check for jumps past the implicit initializer. C++0x
8662 // clarifies that this applies to a "variable with automatic
8663 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00008664 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00008665 // A program that jumps from a point where a variable with automatic
8666 // storage duration is not in scope to a point where it is in scope is
8667 // ill-formed unless the variable has scalar type, class type with a
8668 // trivial default constructor and a trivial destructor, a cv-qualified
8669 // version of one of these types, or an array of one of the preceding
8670 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00008671 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008672 if (const RecordType *Record
8673 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00008674 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00008675 // Mark the function for further checking even if the looser rules of
8676 // C++11 do not require such checks, so that we can diagnose
8677 // incompatibilities with C++98.
8678 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00008679 getCurFunction()->setHasBranchProtectedScope();
8680 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008681 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00008682
8683 // C++03 [dcl.init]p9:
8684 // If no initializer is specified for an object, and the
8685 // object is of (possibly cv-qualified) non-POD class type (or
8686 // array thereof), the object shall be default-initialized; if
8687 // the object is of const-qualified type, the underlying class
8688 // type shall have a user-declared default
8689 // constructor. Otherwise, if no initializer is specified for
8690 // a non- static object, the object and its subobjects, if
8691 // any, have an indeterminate initial value); if the object
8692 // or any of its subobjects are of const-qualified type, the
8693 // program is ill-formed.
8694 // C++0x [dcl.init]p11:
8695 // If no initializer is specified for an object, the object is
8696 // default-initialized; [...].
8697 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8698 InitializationKind Kind
8699 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00008700
8701 InitializationSequence InitSeq(*this, Entity, Kind, None);
8702 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor4337dc72011-05-21 17:52:48 +00008703 if (Init.isInvalid())
8704 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008705 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008706 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008707 // This is important for template substitution.
8708 Var->setInitStyle(VarDecl::CallInit);
8709 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00008710
John McCall2998d6b2011-01-19 11:48:09 +00008711 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008712 }
8713}
8714
Richard Smithad762fc2011-04-14 22:09:26 +00008715void Sema::ActOnCXXForRangeDecl(Decl *D) {
8716 VarDecl *VD = dyn_cast<VarDecl>(D);
8717 if (!VD) {
8718 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8719 D->setInvalidDecl();
8720 return;
8721 }
8722
8723 VD->setCXXForRangeDecl(true);
8724
8725 // for-range-declaration cannot be given a storage class specifier.
8726 int Error = -1;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008727 switch (VD->getStorageClass()) {
Richard Smithad762fc2011-04-14 22:09:26 +00008728 case SC_None:
8729 break;
8730 case SC_Extern:
8731 Error = 0;
8732 break;
8733 case SC_Static:
8734 Error = 1;
8735 break;
8736 case SC_PrivateExtern:
8737 Error = 2;
8738 break;
8739 case SC_Auto:
8740 Error = 3;
8741 break;
8742 case SC_Register:
8743 Error = 4;
8744 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008745 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00008746 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00008747 }
Richard Smithc6d990a2011-09-29 19:11:37 +00008748 if (VD->isConstexpr())
8749 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00008750 if (Error != -1) {
8751 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8752 << VD->getDeclName() << Error;
8753 D->setInvalidDecl();
8754 }
8755}
8756
John McCall2998d6b2011-01-19 11:48:09 +00008757void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8758 if (var->isInvalidDecl()) return;
8759
John McCallf85e1932011-06-15 23:02:42 +00008760 // In ARC, don't allow jumps past the implicit initialization of a
8761 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00008762 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00008763 var->hasLocalStorage()) {
8764 switch (var->getType().getObjCLifetime()) {
8765 case Qualifiers::OCL_None:
8766 case Qualifiers::OCL_ExplicitNone:
8767 case Qualifiers::OCL_Autoreleasing:
8768 break;
8769
8770 case Qualifiers::OCL_Weak:
8771 case Qualifiers::OCL_Strong:
8772 getCurFunction()->setHasBranchProtectedScope();
8773 break;
8774 }
8775 }
8776
Eli Friedmane4851f22012-10-23 20:19:32 +00008777 if (var->isThisDeclarationADefinition() &&
Eli Friedman2ae28e52013-09-24 23:10:08 +00008778 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimekacaf1102012-12-12 13:26:54 +00008779 getDiagnostics().getDiagnosticLevel(
8780 diag::warn_missing_variable_declarations,
8781 var->getLocation())) {
Eli Friedmane4851f22012-10-23 20:19:32 +00008782 // Find a previous declaration that's not a definition.
8783 VarDecl *prev = var->getPreviousDecl();
8784 while (prev && prev->isThisDeclarationADefinition())
8785 prev = prev->getPreviousDecl();
8786
8787 if (!prev)
8788 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8789 }
8790
Richard Smith6a570f62013-04-14 20:11:31 +00008791 if (var->getTLSKind() == VarDecl::TLS_Static &&
8792 var->getType().isDestructedType()) {
8793 // GNU C++98 edits for __thread, [basic.start.term]p3:
8794 // The type of an object with thread storage duration shall not
8795 // have a non-trivial destructor.
8796 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8797 if (getLangOpts().CPlusPlus11)
8798 Diag(var->getLocation(), diag::note_use_thread_local);
8799 }
8800
John McCall2998d6b2011-01-19 11:48:09 +00008801 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00008802 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00008803
Richard Smitha67d5032012-11-09 23:03:14 +00008804 QualType type = var->getType();
8805 if (type->isDependentType()) return;
John McCall2998d6b2011-01-19 11:48:09 +00008806
8807 // __block variables might require us to capture a copy-initializer.
8808 if (var->hasAttr<BlocksAttr>()) {
8809 // It's currently invalid to ever have a __block variable with an
8810 // array type; should we diagnose that here?
8811
8812 // Regardless, we don't want to ignore array nesting when
8813 // constructing this copy.
John McCall2998d6b2011-01-19 11:48:09 +00008814 if (type->isStructureOrClassType()) {
John McCallb760f112013-03-22 02:10:40 +00008815 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall2998d6b2011-01-19 11:48:09 +00008816 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00008817 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregor6cda3e62013-03-07 22:38:24 +00008818 ExprResult result
8819 = PerformMoveOrCopyInitialization(
8820 InitializedEntity::InitializeBlock(poi, type, false),
8821 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall2998d6b2011-01-19 11:48:09 +00008822 if (!result.isInvalid()) {
8823 result = MaybeCreateExprWithCleanups(result);
8824 Expr *init = result.takeAs<Expr>();
8825 Context.setBlockVarCopyInits(var, init);
8826 }
8827 }
8828 }
8829
Richard Smith66f85712011-11-07 22:16:17 +00008830 Expr *Init = var->getInit();
8831 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smitha67d5032012-11-09 23:03:14 +00008832 QualType baseType = Context.getBaseElementType(type);
Richard Smith66f85712011-11-07 22:16:17 +00008833
Richard Smith9568f0c2012-10-29 18:26:47 +00008834 if (!var->getDeclContext()->isDependentContext() &&
8835 Init && !Init->isValueDependent()) {
Richard Smith099e7f62011-12-19 06:19:21 +00008836 if (IsGlobal && !var->isConstexpr() &&
8837 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8838 var->getLocation())
Eli Friedman21cde052013-07-16 22:40:53 +00008839 != DiagnosticsEngine::Ignored) {
8840 // Warn about globals which don't have a constant initializer. Don't
8841 // warn about globals with a non-trivial destructor because we already
8842 // warned about them.
8843 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8844 if (!(RD && !RD->hasTrivialDestructor()) &&
8845 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8846 Diag(var->getLocation(), diag::warn_global_constructor)
8847 << Init->getSourceRange();
8848 }
Richard Smith099e7f62011-12-19 06:19:21 +00008849
Richard Smith099e7f62011-12-19 06:19:21 +00008850 if (var->isConstexpr()) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008851 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00008852 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8853 SourceLocation DiagLoc = var->getLocation();
8854 // If the note doesn't add any useful information other than a source
8855 // location, fold it into the primary diagnostic.
8856 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8857 diag::note_invalid_subexpr_in_const_expr) {
8858 DiagLoc = Notes[0].first;
8859 Notes.clear();
8860 }
8861 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8862 << var << Init->getSourceRange();
8863 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8864 Diag(Notes[I].first, Notes[I].second);
8865 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00008866 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00008867 // Check whether the initializer of a const variable of integral or
8868 // enumeration type is an ICE now, since we can't tell whether it was
8869 // initialized by a constant expression if we check later.
8870 var->checkInitIsICE();
8871 }
Richard Smith66f85712011-11-07 22:16:17 +00008872 }
John McCall2998d6b2011-01-19 11:48:09 +00008873
8874 // Require the destructor.
8875 if (const RecordType *recordType = baseType->getAs<RecordType>())
8876 FinalizeVarWithDestructor(var, recordType);
8877}
8878
Richard Smith483b9f32011-02-21 20:05:19 +00008879/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8880/// any semantic actions necessary after any initializer has been attached.
8881void
8882Sema::FinalizeDeclaration(Decl *ThisDecl) {
8883 // Note that we are no longer parsing the initializer for this declaration.
8884 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008885
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008886 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindolada844b32013-01-03 04:05:19 +00008887 if (!VD)
8888 return;
8889
Rafael Espindola29535ba2013-08-16 23:18:50 +00008890 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8891 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8892 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8893 VD->dropAttr<UsedAttr>();
8894 }
8895 }
8896
Rafael Espindolab1c0e202013-10-22 21:39:03 +00008897 if (!VD->isInvalidDecl() &&
8898 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8899 if (const VarDecl *Def = VD->getDefinition()) {
8900 if (Def->hasAttr<AliasAttr>()) {
8901 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8902 << VD->getDeclName();
8903 Diag(Def->getLocation(), diag::note_previous_definition);
8904 VD->setInvalidDecl();
8905 }
8906 }
8907 }
8908
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008909 const DeclContext *DC = VD->getDeclContext();
8910 // If there's a #pragma GCC visibility in scope, and this isn't a class
8911 // member, set the visibility of this variable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008912 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008913 AddPushedVisibilityAttribute(VD);
8914
Rafael Espindola6769ccb2013-01-03 04:29:20 +00008915 if (VD->isFileVarDecl())
8916 MarkUnusedFileScopedDecl(VD);
8917
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008918 // Now we have parsed the initializer and can update the table of magic
8919 // tag values.
Rafael Espindolada844b32013-01-03 04:05:19 +00008920 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8921 !VD->getType()->isIntegralOrEnumerationType())
8922 return;
8923
8924 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8925 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8926 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8927 I != E; ++I) {
8928 const Expr *MagicValueExpr = VD->getInit();
8929 if (!MagicValueExpr) {
8930 continue;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008931 }
Rafael Espindolada844b32013-01-03 04:05:19 +00008932 llvm::APSInt MagicValueInt;
8933 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8934 Diag(I->getRange().getBegin(),
8935 diag::err_type_tag_for_datatype_not_ice)
8936 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8937 continue;
8938 }
8939 if (MagicValueInt.getActiveBits() > 64) {
8940 Diag(I->getRange().getBegin(),
8941 diag::err_type_tag_for_datatype_too_large)
8942 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8943 continue;
8944 }
8945 uint64_t MagicValue = MagicValueInt.getZExtValue();
8946 RegisterTypeTagForDatatype(I->getArgumentKind(),
8947 MagicValue,
8948 I->getMatchingCType(),
8949 I->getLayoutCompatible(),
8950 I->getMustBeNull());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008951 }
Richard Smith483b9f32011-02-21 20:05:19 +00008952}
8953
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008954Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8955 ArrayRef<Decl *> Group) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00008956 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008957
8958 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00008959 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008960
David Majnemeraa824612013-09-17 23:57:10 +00008961 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008962 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemeraa824612013-09-17 23:57:10 +00008963 if (Decl *D = Group[i]) {
8964 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8965 if (!FirstDeclaratorInGroup)
8966 FirstDeclaratorInGroup = DD;
Richard Smith406c38e2011-02-23 00:37:57 +00008967 Decls.push_back(D);
David Majnemeraa824612013-09-17 23:57:10 +00008968 }
Richard Smith406c38e2011-02-23 00:37:57 +00008969
Eli Friedman5e867c82013-07-10 00:30:46 +00008970 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemeraa824612013-09-17 23:57:10 +00008971 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman5e867c82013-07-10 00:30:46 +00008972 HandleTagNumbering(*this, Tag);
David Majnemeraa824612013-09-17 23:57:10 +00008973 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8974 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8975 }
Eli Friedman5e867c82013-07-10 00:30:46 +00008976 }
David Blaikie66cff722012-11-14 01:52:05 +00008977
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008978 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith406c38e2011-02-23 00:37:57 +00008979}
8980
8981/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8982/// group, performing any necessary semantic checking.
8983Sema::DeclGroupPtrTy
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008984Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith406c38e2011-02-23 00:37:57 +00008985 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00008986 // C++0x [dcl.spec.auto]p7:
8987 // If the type deduced for the template parameter U is not the same in each
8988 // deduction, the program is ill-formed.
8989 // FIXME: When initializer-list support is added, a distinction is needed
8990 // between the deduced type U and the deduced type which 'auto' stands for.
8991 // auto a = 0, b = { 1, 2, 3 };
8992 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008993 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00008994 QualType Deduced;
8995 CanQualType DeducedCanon;
8996 VarDecl *DeducedDecl = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008997 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith34b41d92011-02-20 03:19:35 +00008998 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8999 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00009000 // Don't reissue diagnostics when instantiating a template.
9001 if (AT && D->isInvalidDecl())
9002 break;
Richard Smithdc7a4f52013-04-30 13:56:41 +00009003 QualType U = AT ? AT->getDeducedType() : QualType();
9004 if (!U.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00009005 CanQualType UCanon = Context.getCanonicalType(U);
9006 if (Deduced.isNull()) {
9007 Deduced = U;
9008 DeducedCanon = UCanon;
9009 DeducedDecl = D;
9010 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00009011 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9012 diag::err_auto_different_deductions)
Richard Smithffd015e2013-05-04 04:19:27 +00009013 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith34b41d92011-02-20 03:19:35 +00009014 << Deduced << DeducedDecl->getDeclName()
9015 << U << D->getDeclName()
9016 << DeducedDecl->getInit()->getSourceRange()
9017 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00009018 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00009019 break;
9020 }
9021 }
9022 }
9023 }
9024 }
9025
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009026 ActOnDocumentableDecls(Group);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009027
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009028 return DeclGroupPtrTy::make(
9029 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00009030}
Steve Naroffe1223f72007-08-28 03:03:08 +00009031
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009032void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009033 ActOnDocumentableDecls(D);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009034}
9035
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009036void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009037 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009038 if (Group.empty() || !Group[0])
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009039 return;
9040
9041 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9042 Group[0]->getLocation())
9043 == DiagnosticsEngine::Ignored)
9044 return;
9045
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009046 if (Group.size() >= 2) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009047 // This is a decl group. Normally it will contain only declarations
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009048 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009049 // additional declaration references:
9050 // 'typedef struct S {} S;'
9051 // 'typedef struct S *S;'
9052 // 'struct S *pS;'
9053 // FinalizeDeclaratorGroup adds these as separate declarations.
9054 Decl *MaybeTagDecl = Group[0];
9055 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009056 Group = Group.slice(1);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009057 }
9058 }
9059
9060 // See if there are any new comments that are not attached to a decl.
9061 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9062 if (!Comments.empty() &&
9063 !Comments.back()->isAttached()) {
9064 // There is at least one comment that not attached to a decl.
9065 // Maybe it should be attached to one of these decls?
9066 //
9067 // Note that this way we pick up not only comments that precede the
9068 // declaration, but also comments that *follow* the declaration -- thanks to
9069 // the lookahead in the lexer: we've consumed the semicolon and looked
9070 // ahead through comments.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009071 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko19523542012-09-29 11:40:46 +00009072 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009073 }
9074}
Chris Lattner682bf922009-03-29 16:50:03 +00009075
Chris Lattner04421082008-04-08 04:40:51 +00009076/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9077/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00009078Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00009079 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00009080
Chris Lattner04421082008-04-08 04:40:51 +00009081 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Valifad9e132013-09-26 19:54:12 +00009082
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009083 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00009084 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009085 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00009086 StorageClass = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00009087 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009088 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9089 StorageClass = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009090 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00009091 Diag(DS.getStorageClassSpecLoc(),
9092 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00009093 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00009094 }
Eli Friedman63054b32009-04-19 20:27:55 +00009095
Richard Smithec642442013-04-12 22:46:28 +00009096 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9097 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9098 << DeclSpec::getSpecifierName(TSCS);
9099 if (DS.isConstexprSpecified())
9100 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smithaf1fc7a2011-08-15 21:04:07 +00009101 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00009102
Richard Smithec642442013-04-12 22:46:28 +00009103 DiagnoseFunctionSpecifiers(DS);
Eli Friedman85a53192009-04-07 19:37:57 +00009104
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00009105 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00009106 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009107
David Blaikie4e4d0842012-03-11 07:00:24 +00009108 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009109 // Check that there are no default arguments inside the type of this
9110 // parameter.
9111 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009112
9113 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9114 if (D.getCXXScopeSpec().isSet()) {
9115 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9116 << D.getCXXScopeSpec().getRange();
9117 D.getCXXScopeSpec().clear();
9118 }
Douglas Gregor402abb52009-05-28 23:31:59 +00009119 }
9120
Sean Hunt7533a5b2010-11-03 01:07:06 +00009121 // Ensure we have a valid name
9122 IdentifierInfo *II = 0;
9123 if (D.hasName()) {
9124 II = D.getIdentifier();
9125 if (!II) {
9126 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9127 << GetNameForDeclarator(D).getName().getAsString();
9128 D.setInvalidType(true);
9129 }
9130 }
9131
Chris Lattnerd84aac12010-02-22 00:40:25 +00009132 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00009133 if (II) {
John McCall10f28732010-03-18 06:42:38 +00009134 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9135 ForRedeclaration);
9136 LookupName(R, S);
9137 if (R.isSingleResult()) {
9138 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00009139 if (PrevDecl->isTemplateParameter()) {
9140 // Maybe we will complain about the shadowed template parameter.
9141 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9142 // Just pretend that we didn't see the previous declaration.
9143 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00009144 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00009145 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00009146 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00009147
Chris Lattnercf79b012009-01-21 02:38:50 +00009148 // Recover by removing the name
9149 II = 0;
9150 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009151 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00009152 }
Chris Lattner04421082008-04-08 04:40:51 +00009153 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009154 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00009155
John McCall7a9813c2010-01-22 00:28:27 +00009156 // Temporarily put parameter variables in the translation unit, not
9157 // the enclosing context. This prevents them from accidentally
9158 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009159 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00009160 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009161 D.getIdentifierLoc(), II,
9162 parmDeclType, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009163 StorageClass);
Mike Stump1eb44332009-09-09 15:08:12 +00009164
Chris Lattnereaaebc72009-04-25 08:06:05 +00009165 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00009166 New->setInvalidDecl();
9167
9168 assert(S->isFunctionPrototypeScope());
9169 assert(S->getFunctionPrototypeDepth() >= 1);
9170 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9171 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009172
Douglas Gregor44b43212008-12-11 16:49:14 +00009173 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00009174 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009175 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00009176 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00009177
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009178 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00009179
Douglas Gregore3895852011-09-12 18:37:38 +00009180 if (D.getDeclSpec().isModulePrivateSpecified())
9181 Diag(New->getLocation(), diag::err_module_private_local)
9182 << 1 << New->getDeclName()
9183 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9184 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9185
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009186 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00009187 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9188 }
John McCalld226f652010-08-21 09:40:31 +00009189 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00009190}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00009191
John McCall82dc0092010-06-04 11:21:44 +00009192/// \brief Synthesizes a variable for a parameter arising from a
9193/// typedef.
9194ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9195 SourceLocation Loc,
9196 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009197 /* FIXME: setting StartLoc == Loc.
9198 Would it be worth to modify callers so as to provide proper source
9199 location for the unnamed parameters, embedding the parameter's type? */
9200 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00009201 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009202 SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00009203 Param->setImplicit();
9204 return Param;
9205}
9206
John McCallfbce0e12010-08-24 09:05:15 +00009207void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9208 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00009209 // Don't diagnose unused-parameter errors in template instantiations; we
9210 // will already have done so in the template itself.
9211 if (!ActiveTemplateInstantiations.empty())
9212 return;
9213
9214 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00009215 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00009216 !(*Param)->hasAttr<UnusedAttr>()) {
9217 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9218 << (*Param)->getDeclName();
9219 }
9220 }
9221}
9222
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009223void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9224 ParmVarDecl * const *ParamEnd,
9225 QualType ReturnTy,
9226 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009227 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009228 return;
9229
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009230 // Warn if the return value is pass-by-value and larger than the specified
9231 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00009232 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009233 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009234 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009235 Diag(D->getLocation(), diag::warn_return_value_size)
9236 << D->getDeclName() << Size;
9237 }
9238
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009239 // Warn if any parameter is pass-by-value and larger than the specified
9240 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009241 for (; Param != ParamEnd; ++Param) {
9242 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00009243 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009244 continue;
9245 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009246 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009247 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9248 << (*Param)->getDeclName() << Size;
9249 }
9250}
9251
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009252ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9253 SourceLocation NameLoc, IdentifierInfo *Name,
9254 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009255 VarDecl::StorageClass StorageClass) {
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009256 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00009257 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009258 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009259 T->isObjCLifetimeType()) {
9260
9261 Qualifiers::ObjCLifetime lifetime;
9262
9263 // Special cases for arrays:
9264 // - if it's const, use __unsafe_unretained
9265 // - otherwise, it's an error
9266 if (T->isArrayType()) {
9267 if (!T.isConstQualified()) {
9268 DelayedDiagnostics.add(
9269 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanian175fb102011-10-03 22:11:57 +00009270 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009271 }
9272 lifetime = Qualifiers::OCL_ExplicitNone;
9273 } else {
9274 lifetime = T->getObjCARCImplicitLifetime();
9275 }
9276 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCallf85e1932011-06-15 23:02:42 +00009277 }
9278
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009279 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00009280 Context.getAdjustedParameterType(T),
9281 TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009282 StorageClass, 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009283
9284 // Parameters can not be abstract class types.
9285 // For record types, this is done by the AbstractClassUsageDiagnoser once
9286 // the class has been completely parsed.
9287 if (!CurContext->isRecord() &&
9288 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9289 AbstractParamType))
9290 New->setInvalidDecl();
9291
9292 // Parameter declarators cannot be interface types. All ObjC objects are
9293 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00009294 if (T->isObjCObjectType()) {
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009295 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009296 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009297 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009298 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009299 T = Context.getObjCObjectPointerType(T);
9300 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009301 }
9302
9303 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9304 // duration shall not be qualified by an address-space qualifier."
9305 // Since all parameters have automatic store duration, they can not have
9306 // an address space.
9307 if (T.getAddressSpace() != 0) {
9308 Diag(NameLoc, diag::err_arg_with_address_space);
9309 New->setInvalidDecl();
9310 }
9311
9312 return New;
9313}
9314
Douglas Gregora3a83512009-04-01 23:51:29 +00009315void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9316 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009317 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00009318
Reid Spencer5f016e22007-07-11 17:01:13 +00009319 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9320 // for a K&R function.
9321 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00009322 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9323 --i;
Chris Lattner04421082008-04-08 04:40:51 +00009324 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009325 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009326 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009327 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009328 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00009329 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00009330 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00009331 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00009332
Reid Spencer5f016e22007-07-11 17:01:13 +00009333 // Implicitly declare the argument as type 'int' for lack of a better
9334 // type.
John McCall0b7e6782011-03-24 11:26:52 +00009335 AttributeFactory attrs;
9336 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00009337 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00009338 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00009339 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00009340 PrevSpec, DiagID);
Abramo Bagnara16467f22012-10-04 21:38:29 +00009341 // Use the identifier location for the type source range.
9342 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9343 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattner04421082008-04-08 04:40:51 +00009344 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9345 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00009346 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00009347 }
9348 }
Mike Stump1eb44332009-09-09 15:08:12 +00009349 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00009350}
9351
Richard Smith87162c22012-04-17 22:30:01 +00009352Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00009353 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009354 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00009355 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00009356
Douglas Gregor45fa5602011-11-07 20:56:01 +00009357 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009358 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner682bf922009-03-29 16:50:03 +00009359 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00009360}
9361
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009362static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9363 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009364 // Don't warn about invalid declarations.
9365 if (FD->isInvalidDecl())
9366 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009367
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009368 // Or declarations that aren't global.
9369 if (!FD->isGlobal())
9370 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009371
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009372 // Don't warn about C++ member functions.
9373 if (isa<CXXMethodDecl>(FD))
9374 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009375
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009376 // Don't warn about 'main'.
9377 if (FD->isMain())
9378 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009379
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009380 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00009381 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009382 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009383
9384 // Don't warn about function templates.
9385 if (FD->getDescribedFunctionTemplate())
9386 return false;
9387
9388 // Don't warn about function template specializations.
9389 if (FD->isFunctionTemplateSpecialization())
9390 return false;
9391
Tanya Lattnera95b4f72012-07-26 00:08:28 +00009392 // Don't warn for OpenCL kernels.
9393 if (FD->hasAttr<OpenCLKernelAttr>())
9394 return false;
Richard Smitha41c97a2013-09-20 01:15:31 +00009395
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009396 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00009397 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9398 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009399 // Ignore any declarations that occur in function or method
9400 // scope, because they aren't visible from the header.
Richard Smitha41c97a2013-09-20 01:15:31 +00009401 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009402 continue;
Richard Smitha41c97a2013-09-20 01:15:31 +00009403
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009404 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009405 if (FD->getNumParams() == 0)
9406 PossibleZeroParamPrototype = Prev;
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009407 break;
9408 }
Richard Smitha41c97a2013-09-20 01:15:31 +00009409
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009410 return MissingPrototype;
9411}
9412
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009413void
9414Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9415 const FunctionDecl *EffectiveDefinition) {
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009416 // Don't complain if we're in GNU89 mode and the previous definition
9417 // was an extern inline function.
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009418 const FunctionDecl *Definition = EffectiveDefinition;
9419 if (!Definition)
9420 if (!FD->isDefined(Definition))
9421 return;
9422
9423 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009424 return;
9425
9426 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9427 Definition->getStorageClass() == SC_Extern)
9428 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00009429 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009430 else
9431 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9432
9433 Diag(Definition->getLocation(), diag::note_previous_definition);
9434 FD->setInvalidDecl();
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009435}
Faisal Valic00e4192013-11-07 05:17:06 +00009436
9437
Faisal Valibef582b2013-10-23 16:10:50 +00009438static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9439 Sema &S) {
9440 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Valid78d6592013-11-12 01:40:44 +00009441
9442 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valibef582b2013-10-23 16:10:50 +00009443 LSI->CallOperator = CallOperator;
9444 LSI->Lambda = LambdaClass;
9445 LSI->ReturnType = CallOperator->getResultType();
9446 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9447
9448 if (LCD == LCD_None)
9449 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9450 else if (LCD == LCD_ByCopy)
9451 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9452 else if (LCD == LCD_ByRef)
9453 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9454 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9455
9456 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9457 LSI->Mutable = !CallOperator->isConst();
9458
Faisal Valic00e4192013-11-07 05:17:06 +00009459 // Add the captures to the LSI so they can be noted as already
9460 // captured within tryCaptureVar.
9461 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9462 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9463 if (C->capturesVariable()) {
9464 VarDecl *VD = C->getCapturedVar();
9465 if (VD->isInitCapture())
9466 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9467 QualType CaptureType = VD->getType();
9468 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9469 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9470 /*RefersToEnclosingLocal*/true, C->getLocation(),
9471 /*EllipsisLoc*/C->isPackExpansion()
9472 ? C->getEllipsisLoc() : SourceLocation(),
9473 CaptureType, /*Expr*/ 0);
9474
9475 } else if (C->capturesThis()) {
9476 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9477 S.getCurrentThisType(), /*Expr*/ 0);
9478 }
9479 }
Faisal Valibef582b2013-10-23 16:10:50 +00009480}
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009481
John McCalld226f652010-08-21 09:40:31 +00009482Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00009483 // Clear the last template instantiation error context.
9484 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9485
Douglas Gregor52591bf2009-06-24 00:54:41 +00009486 if (!D)
9487 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00009488 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00009489
John McCalld226f652010-08-21 09:40:31 +00009490 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00009491 FD = FunTmpl->getTemplatedDecl();
9492 else
John McCalld226f652010-08-21 09:40:31 +00009493 FD = cast<FunctionDecl>(D);
Faisal Valifad9e132013-09-26 19:54:12 +00009494 // If we are instantiating a generic lambda call operator, push
9495 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valibef582b2013-10-23 16:10:50 +00009496 // that's already been calculated (ActOnLambdaExpr) to prime the current
9497 // LambdaScopeInfo.
9498 // When the template operator is being specialized, the LambdaScopeInfo,
9499 // has to be properly restored so that tryCaptureVariable doesn't try
9500 // and capture any new variables. In addition when calculating potential
9501 // captures during transformation of nested lambdas, it is necessary to
9502 // have the LSI properly restored.
Faisal Vali998c5182013-09-29 20:15:45 +00009503 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Valifad9e132013-09-26 19:54:12 +00009504 assert(ActiveTemplateInstantiations.size() &&
9505 "There should be an active template instantiation on the stack "
9506 "when instantiating a generic lambda!");
Faisal Valibef582b2013-10-23 16:10:50 +00009507 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Valifad9e132013-09-26 19:54:12 +00009508 }
9509 else
9510 // Enter a new function scope
9511 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00009512
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009513 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009514 if (!FD->isLateTemplateParsed())
9515 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009516
Douglas Gregorcda9c672009-02-16 17:45:42 +00009517 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009518 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindolaad24ad42013-06-13 18:34:17 +00009519 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9520 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00009521 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00009522 FD->setInvalidDecl();
9523 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00009524 }
9525
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009526 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00009527 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9528 QualType ResultType = FD->getResultType();
9529 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00009530 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00009531 RequireCompleteType(FD->getLocation(), ResultType,
9532 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009533 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009534
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009535 // GNU warning -Wmissing-prototypes:
9536 // Warn if a global function is defined without a previous
9537 // prototype declaration. This warning is issued even if the
9538 // definition itself provides a prototype. The aim is to detect
9539 // global functions that fail to be declared in header files.
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009540 const FunctionDecl *PossibleZeroParamPrototype = 0;
9541 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009542 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithac83a3c2013-06-25 20:34:17 +00009543
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009544 if (PossibleZeroParamPrototype) {
Richard Smithac83a3c2013-06-25 20:34:17 +00009545 // We found a declaration that is not a prototype,
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009546 // but that could be a zero-parameter prototype
Richard Smithac83a3c2013-06-25 20:34:17 +00009547 if (TypeSourceInfo *TI =
9548 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9549 TypeLoc TL = TI->getTypeLoc();
9550 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9551 Diag(PossibleZeroParamPrototype->getLocation(),
9552 diag::note_declaration_not_a_prototype)
9553 << PossibleZeroParamPrototype
9554 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9555 }
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009556 }
9557 }
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009558
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009559 if (FnBodyScope)
9560 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009561
Chris Lattner04421082008-04-08 04:40:51 +00009562 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00009563 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9564 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00009565
9566 // Introduce our parameters into the function scope
9567 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9568 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00009569 Param->setOwningFunction(FD);
9570
Chris Lattner04421082008-04-08 04:40:51 +00009571 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009572 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009573 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00009574
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009575 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00009576 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009577 }
Chris Lattner04421082008-04-08 04:40:51 +00009578
James Molloy16f1f712012-02-29 10:24:19 +00009579 // If we had any tags defined in the function prototype,
9580 // introduce them into the function scope.
9581 if (FnBodyScope) {
Robert Wilhelm834c0582013-08-09 18:02:13 +00009582 for (ArrayRef<NamedDecl *>::iterator
9583 I = FD->getDeclsInPrototypeScope().begin(),
9584 E = FD->getDeclsInPrototypeScope().end();
9585 I != E; ++I) {
James Molloy16f1f712012-02-29 10:24:19 +00009586 NamedDecl *D = *I;
9587
9588 // Some of these decls (like enums) may have been pinned to the translation unit
9589 // for lack of a real context earlier. If so, remove from the translation unit
9590 // and reattach to the current context.
9591 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9592 // Is the decl actually in the context?
9593 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9594 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9595 if (*DI == D) {
9596 Context.getTranslationUnitDecl()->removeDecl(D);
9597 break;
9598 }
9599 }
9600 // Either way, reassign the lexical decl context to our FunctionDecl.
9601 D->setLexicalDeclContext(CurContext);
9602 }
9603
9604 // If the decl has a non-null name, make accessible in the current scope.
9605 if (!D->getName().empty())
9606 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9607
9608 // Similarly, dive into enums and fish their constants out, making them
9609 // accessible in this scope.
9610 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9611 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9612 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie581deb32012-06-06 20:45:41 +00009613 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy16f1f712012-02-29 10:24:19 +00009614 }
9615 }
9616 }
9617
Richard Smith87162c22012-04-17 22:30:01 +00009618 // Ensure that the function's exception specification is instantiated.
9619 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9620 ResolveExceptionSpec(D->getLocation(), FPT);
9621
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009622 // Checking attributes of current function definition
9623 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00009624 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9625 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9626 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00009627 // Microsoft accepts dllimport for functions defined within class scope.
9628 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00009629 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009630 Diag(FD->getLocation(),
9631 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9632 << "dllimport";
9633 FD->setInvalidDecl();
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009634 return D;
Ted Kremenek12911a82010-02-21 05:12:53 +00009635 }
9636
9637 // Visual C++ appears to not think this is an issue, so only issue
9638 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009639 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009640 // If a symbol previously declared dllimport is later defined, the
9641 // attribute is ignored in subsequent references, and a warning is
9642 // emitted.
9643 Diag(FD->getLocation(),
9644 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00009645 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009646 }
9647 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +00009648 // We want to attach documentation to original Decl (which might be
9649 // a function template).
9650 ActOnDocumentableDecl(D);
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009651 return D;
Reid Spencer5f016e22007-07-11 17:01:13 +00009652}
9653
Douglas Gregor5077c382010-05-15 06:01:05 +00009654/// \brief Given the set of return statements within a function body,
9655/// compute the variables that are subject to the named return value
9656/// optimization.
9657///
9658/// Each of the variables that is subject to the named return value
9659/// optimization will be marked as NRVO variables in the AST, and any
9660/// return statement that has a marked NRVO variable as its NRVO candidate can
9661/// use the named return value optimization.
9662///
9663/// This function applies a very simplistic algorithm for NRVO: if every return
9664/// statement in the function has the same NRVO candidate, that candidate is
9665/// the NRVO variable.
9666///
9667/// FIXME: Employ a smarter algorithm that accounts for multiple return
9668/// statements and the lifetimes of the NRVO candidates. We should be able to
9669/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009670void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00009671 ReturnStmt **Returns = Scope->Returns.data();
9672
Douglas Gregor5077c382010-05-15 06:01:05 +00009673 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00009674 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00009675 if (!Returns[I]->getNRVOCandidate())
9676 return;
9677
9678 if (!NRVOCandidate)
9679 NRVOCandidate = Returns[I]->getNRVOCandidate();
9680 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9681 return;
9682 }
9683
9684 if (NRVOCandidate)
9685 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9686}
9687
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009688bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smithd1bac8d2012-11-27 21:31:01 +00009689 if (!Consumer.shouldSkipFunctionBody(D))
9690 return false;
9691
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009692 if (isa<ObjCMethodDecl>(D))
9693 return true;
9694
9695 FunctionDecl *FD = 0;
9696 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9697 FD = FTD->getTemplatedDecl();
9698 else
9699 FD = cast<FunctionDecl>(D);
9700
9701 // We cannot skip the body of a function (or function template) which is
9702 // constexpr, since we may need to evaluate its body in order to parse the
9703 // rest of the file.
Richard Smith25d8c852013-05-10 04:31:10 +00009704 // We cannot skip the body of a function with an undeduced return type,
9705 // because any callers of that function need to know the type.
9706 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009707}
9708
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009709Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009710 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009711 FD->setHasSkippedBody();
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009712 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009713 MD->setHasSkippedBody();
9714 return ActOnFinishFunctionBody(Decl, 0);
9715}
9716
John McCallf312b1e2010-08-26 23:41:50 +00009717Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009718 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009719}
9720
John McCall9ae2f072010-08-23 23:25:46 +00009721Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9722 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00009723 FunctionDecl *FD = 0;
9724 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9725 if (FunTmpl)
9726 FD = FunTmpl->getTemplatedDecl();
9727 else
9728 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9729
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009730 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009731 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009732
Douglas Gregord83d0402009-08-22 00:34:47 +00009733 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00009734 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00009735
Richard Smith25d8c852013-05-10 04:31:10 +00009736 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9737 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9738 // If the function has a deduced result type but contains no 'return'
9739 // statements, the result type as written must be exactly 'auto', and
9740 // the deduced result type is 'void'.
9741 if (!FD->getResultType()->getAs<AutoType>()) {
9742 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9743 << FD->getResultType();
9744 FD->setInvalidDecl();
9745 } else {
9746 // Substitute 'void' for the 'auto' in the type.
9747 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9748 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9749 Context.adjustDeducedFunctionResultType(
9750 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith60e141e2013-05-04 07:00:32 +00009751 }
9752 }
9753
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009754 // The only way to be included in UndefinedButUsed is if there is an
9755 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewycky995e26b2013-01-31 03:23:57 +00009756 // is the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00009757 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00009758 if (!FD->isExternallyVisible())
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009759 UndefinedButUsed.erase(FD);
9760 else if (FD->isInlined() &&
9761 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9762 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9763 UndefinedButUsed.erase(FD);
9764 }
Nick Lewycky995e26b2013-01-31 03:23:57 +00009765
John McCall75d8ba32012-02-14 19:50:52 +00009766 // If the function implicitly returns zero (like 'main') or is naked,
9767 // don't complain about missing return statements.
9768 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009769 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00009770
Francois Pichet6a247472011-05-11 02:14:46 +00009771 // MSVC permits the use of pure specifier (=0) on function definition,
9772 // defined at class scope, warn about this non standard construct.
Reid Kleckner5dbed662013-10-08 22:45:29 +00009773 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet6a247472011-05-11 02:14:46 +00009774 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9775
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009776 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009777 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009778 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9779 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009780
9781 // If this is a constructor, we need a vtable.
9782 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9783 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00009784
Jordan Rose7dd900e2012-07-02 21:19:23 +00009785 // Try to apply the named return value optimization. We have to check
9786 // if we can do this here because lambdas keep return statements around
9787 // to deduce an implicit return type.
9788 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9789 !FD->isDependentContext())
9790 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009791 }
9792
Douglas Gregor76e3da52012-02-08 20:17:14 +00009793 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9794 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00009795 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00009796 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00009797 MD->setBody(Body);
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009798 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009799 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009800 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9801 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00009802
9803 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009804 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009805 }
Jordan Rose535a5d02012-10-19 16:05:26 +00009806 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanian9f559832012-09-10 16:51:09 +00009807 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9808 << MD->getSelector().getAsString();
Jordan Rose535a5d02012-10-19 16:05:26 +00009809 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00009810 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00009811 } else {
John McCalld226f652010-08-21 09:40:31 +00009812 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00009813 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009814
Jordan Rose535a5d02012-10-19 16:05:26 +00009815 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman95aac152012-08-01 21:02:59 +00009816 "This should only be set for ObjC methods, which should have been "
9817 "handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00009818
Reid Spencer5f016e22007-07-11 17:01:13 +00009819 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009820 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009821 // C++ constructors that have function-try-blocks can't have return
9822 // statements in the handlers of that block. (C++ [except.handle]p14)
9823 // Verify this.
9824 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9825 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9826
Richard Smith37bee672011-08-12 18:44:32 +00009827 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00009828 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00009829 !dcl->isInvalidDecl() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009830 !hasAnyUnrecoverableErrorsInThisFunction() &&
9831 !PP.isCodeCompletionEnabled())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009832 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00009833
John McCall15442822010-08-04 01:04:25 +00009834 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9835 if (!Destructor->getParent()->isDependentType())
9836 CheckDestructor(Destructor);
9837
John McCallef027fe2010-03-16 21:39:52 +00009838 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9839 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00009840 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009841
9842 // If any errors have occurred, clear out any temporaries that may have
9843 // been leftover. This ensures that these temporaries won't be picked up for
9844 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00009845 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00009846 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00009847 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00009848 }
9849 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9850 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009851 // Since the body is valid, issue any analysis-based warnings that are
9852 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009853 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009854 }
9855
Richard Smith86c3ae42012-02-13 03:54:03 +00009856 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9857 (!CheckConstexprFunctionDecl(FD) ||
9858 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00009859 FD->setInvalidDecl();
9860
John McCall80ee6e82011-11-10 05:35:25 +00009861 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00009862 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00009863 assert(MaybeODRUseExprs.empty() &&
9864 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009865 }
9866
John McCall90f97892010-03-25 22:08:03 +00009867 if (!IsInstantiation)
9868 PopDeclContext();
9869
Eli Friedmanec9ea722012-01-05 03:35:19 +00009870 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregord5b57282009-11-15 07:07:58 +00009871 // If any errors have occurred, clear out any temporaries that may have
9872 // been leftover. This ensures that these temporaries won't be picked up for
9873 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00009874 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00009875 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00009876 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00009877
John McCalld226f652010-08-21 09:40:31 +00009878 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00009879}
9880
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009881
9882/// When we finish delayed parsing of an attribute, we must attach it to the
9883/// relevant Decl.
9884void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9885 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00009886 // Always attach attributes to the underlying decl.
9887 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9888 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00009889 ProcessDeclAttributeList(S, D, Attrs.getList());
9890
9891 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9892 if (Method->isStatic())
9893 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009894}
9895
9896
Reid Spencer5f016e22007-07-11 17:01:13 +00009897/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9898/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00009899NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00009900 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00009901 // Before we produce a declaration for an implicitly defined
9902 // function, see whether there was a locally-scoped declaration of
9903 // this name as a function or variable. If so, use that
9904 // (non-visible) declaration, and complain about it.
Richard Smith662f41b2013-06-18 20:15:12 +00009905 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9906 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9907 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9908 return ExternCPrev;
Douglas Gregor63935192009-03-02 00:19:53 +00009909 }
9910
Chris Lattner37d10842008-05-05 21:18:06 +00009911 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009912 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009913 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00009914 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00009915 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009916 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00009917 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009918 diag_id = diag::warn_implicit_function_decl;
9919 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00009920
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009921 // Because typo correction is expensive, only do it if the implicit
9922 // function declaration is going to be treated as an error.
9923 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9924 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00009925 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009926 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smith2d670972013-08-17 00:46:16 +00009927 LookupOrdinaryName, S, 0, Validator)))
9928 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9929 /*ErrorRecovery*/false);
Hans Wennborg122de3e2011-12-06 09:46:12 +00009930 }
9931
Reid Spencer5f016e22007-07-11 17:01:13 +00009932 // Set a Declarator for the implicit definition: int foo();
9933 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00009934 AttributeFactory attrFactory;
9935 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00009936 unsigned DiagID;
9937 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00009938 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00009939 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009940 SourceLocation NoLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009941 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009942 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9943 /*IsAmbiguous=*/false,
9944 /*RParenLoc=*/NoLoc,
9945 /*ArgInfo=*/0,
9946 /*NumArgs=*/0,
9947 /*EllipsisLoc=*/NoLoc,
9948 /*RParenLoc=*/NoLoc,
9949 /*TypeQuals=*/0,
9950 /*RefQualifierIsLvalueRef=*/true,
9951 /*RefQualifierLoc=*/NoLoc,
9952 /*ConstQualifierLoc=*/NoLoc,
9953 /*VolatileQualifierLoc=*/NoLoc,
9954 /*MutableLoc=*/NoLoc,
9955 EST_None,
9956 /*ESpecLoc=*/NoLoc,
9957 /*Exceptions=*/0,
9958 /*ExceptionRanges=*/0,
9959 /*NumExceptions=*/0,
9960 /*NoexceptExpr=*/0,
9961 Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00009962 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00009963 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00009964 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00009965
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009966 // Insert this function into translation-unit scope.
9967
9968 DeclContext *PrevDC = CurContext;
9969 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009970
Jordan Rose41f3f3a2013-03-05 01:27:54 +00009971 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00009972 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009973
9974 CurContext = PrevDC;
9975
Douglas Gregor3c385e52009-02-14 18:57:46 +00009976 AddKnownFunctionAttributes(FD);
9977
Steve Naroffe2ef8152008-04-04 14:32:09 +00009978 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009979}
9980
Douglas Gregor3c385e52009-02-14 18:57:46 +00009981/// \brief Adds any function attributes that we know a priori based on
9982/// the declaration of this function.
9983///
9984/// These attributes can apply both to implicitly-declared builtins
9985/// (like __builtin___printf_chk) or to library-declared functions
9986/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009987///
9988/// We need to check for duplicate attributes both here and where user-written
9989/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +00009990void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9991 if (FD->isInvalidDecl())
9992 return;
9993
9994 // If this is a built-in function, map its builtin attributes to
9995 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009996 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00009997 // Handle printf-formatting attributes.
9998 unsigned FormatIdx;
9999 bool HasVAListArg;
10000 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010001 if (!FD->getAttr<FormatAttr>()) {
10002 const char *fmt = "printf";
10003 unsigned int NumParams = FD->getNumParams();
10004 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10005 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10006 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +000010007 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010008 &Context.Idents.get(fmt),
10009 FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +000010010 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010011 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010012 }
Ted Kremenekbee05c12010-07-16 02:11:15 +000010013 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10014 HasVAListArg)) {
10015 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010016 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010017 &Context.Idents.get("scanf"),
10018 FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +000010019 HasVAListArg ? 0 : FormatIdx+2));
10020 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010021
10022 // Mark const if we don't care about errno and that is the only
10023 // thing preventing the function from being const. This allows
10024 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +000010025 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010026 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010027 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010028 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010029 }
Mike Stump0feecbb2009-07-27 19:14:18 +000010030
Rafael Espindola67004152011-10-12 19:51:18 +000010031 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10032 !FD->getAttr<ReturnsTwiceAttr>())
10033 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010034 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010035 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010036 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010037 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +000010038 }
10039
10040 IdentifierInfo *Name = FD->getIdentifier();
10041 if (!Name)
10042 return;
David Blaikie4e4d0842012-03-11 07:00:24 +000010043 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +000010044 FD->getDeclContext()->isTranslationUnit()) ||
10045 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +000010046 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +000010047 LinkageSpecDecl::lang_c)) {
10048 // Okay: this could be a libc/libm/Objective-C function we know
10049 // about.
10050 } else
10051 return;
10052
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010053 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +000010054 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +000010055 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010056 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010057 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010058 &Context.Idents.get("printf"), 2,
Eli Friedmand7dad722009-06-10 04:01:38 +000010059 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +000010060 }
Jordan Rose8a64f882012-08-08 21:17:31 +000010061
10062 if (Name->isStr("__CFStringMakeConstantString")) {
10063 // We already have a __builtin___CFStringMakeConstantString,
10064 // but builds that use -fno-constant-cfstrings don't go through that.
10065 if (!FD->getAttr<FormatArgAttr>())
10066 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10067 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010068}
Reid Spencer5f016e22007-07-11 17:01:13 +000010069
John McCallba6a9bd2009-10-24 08:00:42 +000010070TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000010071 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010072 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +000010073 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +000010074
John McCalla93c9342009-12-07 02:54:59 +000010075 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +000010076 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +000010077 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +000010078 }
10079
Reid Spencer5f016e22007-07-11 17:01:13 +000010080 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +000010081 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010082 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +000010083 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +000010084 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +000010085 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +000010086
John McCallcde5a402011-02-01 08:20:08 +000010087 // Bail out immediately if we have an invalid declaration.
10088 if (D.isInvalidType()) {
10089 NewTD->setInvalidDecl();
10090 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +000010091 }
10092
Douglas Gregore3895852011-09-12 18:37:38 +000010093 if (D.getDeclSpec().isModulePrivateSpecified()) {
10094 if (CurContext->isFunctionOrMethod())
10095 Diag(NewTD->getLocation(), diag::err_module_private_local)
10096 << 2 << NewTD->getDeclName()
10097 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10098 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10099 else
10100 NewTD->setModulePrivate();
10101 }
Douglas Gregor8d267c52011-09-09 02:06:17 +000010102
John McCallcde5a402011-02-01 08:20:08 +000010103 // C++ [dcl.typedef]p8:
10104 // If the typedef declaration defines an unnamed class (or
10105 // enum), the first typedef-name declared by the declaration
10106 // to be that class type (or enum type) is used to denote the
10107 // class type (or enum type) for linkage purposes only.
10108 // We need to check whether the type was declared in the declaration.
10109 switch (D.getDeclSpec().getTypeSpecType()) {
10110 case TST_enum:
10111 case TST_struct:
Joao Matos6666ed42012-08-31 18:45:21 +000010112 case TST_interface:
John McCallcde5a402011-02-01 08:20:08 +000010113 case TST_union:
10114 case TST_class: {
10115 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10116
10117 // Do nothing if the tag is not anonymous or already has an
10118 // associated typedef (from an earlier typedef in this decl group).
10119 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +000010120 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +000010121
10122 // A well-formed anonymous tag must always be a TUK_Definition.
10123 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10124
10125 // The type must match the tag exactly; no qualifiers allowed.
10126 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10127 break;
10128
10129 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +000010130 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +000010131 break;
10132 }
10133
10134 default:
10135 break;
10136 }
10137
Steve Naroff5912a352007-08-28 20:14:24 +000010138 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +000010139}
10140
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010141
Richard Smithf1c66b42012-03-14 23:13:10 +000010142/// \brief Check that this is a valid underlying type for an enum declaration.
10143bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10144 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10145 QualType T = TI->getType();
10146
Eli Friedman2fcff832012-12-18 02:37:32 +000010147 if (T->isDependentType())
Richard Smithf1c66b42012-03-14 23:13:10 +000010148 return false;
10149
Eli Friedman2fcff832012-12-18 02:37:32 +000010150 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10151 if (BT->isInteger())
10152 return false;
10153
Richard Smithf1c66b42012-03-14 23:13:10 +000010154 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10155 return true;
10156}
10157
10158/// Check whether this is a valid redeclaration of a previous enumeration.
10159/// \return true if the redeclaration was invalid.
10160bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10161 QualType EnumUnderlyingTy,
10162 const EnumDecl *Prev) {
10163 bool IsFixed = !EnumUnderlyingTy.isNull();
10164
10165 if (IsScoped != Prev->isScoped()) {
10166 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10167 << Prev->isScoped();
10168 Diag(Prev->getLocation(), diag::note_previous_use);
10169 return true;
10170 }
10171
10172 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +000010173 if (!EnumUnderlyingTy->isDependentType() &&
10174 !Prev->getIntegerType()->isDependentType() &&
10175 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +000010176 Prev->getIntegerType())) {
10177 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10178 << EnumUnderlyingTy << Prev->getIntegerType();
10179 Diag(Prev->getLocation(), diag::note_previous_use);
10180 return true;
10181 }
10182 } else if (IsFixed != Prev->isFixed()) {
10183 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10184 << Prev->isFixed();
10185 Diag(Prev->getLocation(), diag::note_previous_use);
10186 return true;
10187 }
10188
10189 return false;
10190}
10191
Joao Matos6666ed42012-08-31 18:45:21 +000010192/// \brief Get diagnostic %select index for tag kind for
10193/// redeclaration diagnostic message.
10194/// WARNING: Indexes apply to particular diagnostics only!
10195///
10196/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +000010197static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +000010198 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +000010199 case TTK_Struct: return 0;
10200 case TTK_Interface: return 1;
10201 case TTK_Class: return 2;
10202 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +000010203 }
Joao Matos6666ed42012-08-31 18:45:21 +000010204}
10205
10206/// \brief Determine if tag kind is a class-key compatible with
10207/// class for redeclaration (class, struct, or __interface).
10208///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000010209/// \returns true iff the tag kind is compatible.
Joao Matos6666ed42012-08-31 18:45:21 +000010210static bool isClassCompatTagKind(TagTypeKind Tag)
10211{
10212 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10213}
10214
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010215/// \brief Determine whether a tag with a given kind is acceptable
10216/// as a redeclaration of the given tag declaration.
10217///
10218/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +000010219bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +000010220 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010221 SourceLocation NewTagLoc,
10222 const IdentifierInfo &Name) {
10223 // C++ [dcl.type.elab]p3:
10224 // The class-key or enum keyword present in the
10225 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010226 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010227 // refers. This rule also applies to the form of
10228 // elaborated-type-specifier that declares a class-name or
10229 // friend class since it can be construed as referring to the
10230 // definition of the class. Thus, in any
10231 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010232 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010233 // used to refer to a union (clause 9), and either the class or
10234 // struct class-key shall be used to refer to a class (clause 9)
10235 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010236 TagTypeKind OldTag = Previous->getTagKind();
Joao Matos6666ed42012-08-31 18:45:21 +000010237 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieubbf34c02011-06-10 03:11:26 +000010238 if (OldTag == NewTag)
10239 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010240
Joao Matos6666ed42012-08-31 18:45:21 +000010241 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010242 // Warn about the struct/class tag mismatch.
10243 bool isTemplate = false;
10244 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10245 isTemplate = Record->getDescribedClassTemplate();
10246
Richard Trieubbf34c02011-06-10 03:11:26 +000010247 if (!ActiveTemplateInstantiations.empty()) {
10248 // In a template instantiation, do not offer fix-its for tag mismatches
10249 // since they usually mess up the template instead of fixing the problem.
10250 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010251 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10252 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010253 return true;
10254 }
10255
10256 if (isDefinition) {
10257 // On definitions, check previous tags and issue a fix-it for each
10258 // one that doesn't match the current tag.
10259 if (Previous->getDefinition()) {
10260 // Don't suggest fix-its for redefinitions.
10261 return true;
10262 }
10263
10264 bool previousMismatch = false;
10265 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10266 E(Previous->redecls_end()); I != E; ++I) {
10267 if (I->getTagKind() != NewTag) {
10268 if (!previousMismatch) {
10269 previousMismatch = true;
10270 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010271 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10272 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieubbf34c02011-06-10 03:11:26 +000010273 }
10274 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010275 << getRedeclDiagFromTagKind(NewTag)
Richard Trieubbf34c02011-06-10 03:11:26 +000010276 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matos6666ed42012-08-31 18:45:21 +000010277 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieubbf34c02011-06-10 03:11:26 +000010278 }
10279 }
10280 return true;
10281 }
10282
10283 // Check for a previous definition. If current tag and definition
10284 // are same type, do nothing. If no definition, but disagree with
10285 // with previous tag type, give a warning, but no fix-it.
10286 const TagDecl *Redecl = Previous->getDefinition() ?
10287 Previous->getDefinition() : Previous;
10288 if (Redecl->getTagKind() == NewTag) {
10289 return true;
10290 }
10291
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010292 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010293 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10294 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010295 Diag(Redecl->getLocation(), diag::note_previous_use);
10296
10297 // If there is a previous defintion, suggest a fix-it.
10298 if (Previous->getDefinition()) {
10299 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010300 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieubbf34c02011-06-10 03:11:26 +000010301 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matos6666ed42012-08-31 18:45:21 +000010302 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieubbf34c02011-06-10 03:11:26 +000010303 }
10304
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010305 return true;
10306 }
10307 return false;
10308}
10309
Steve Naroff08d92e42007-09-15 18:49:24 +000010310/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +000010311/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +000010312/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +000010313/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +000010314Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +000010315 SourceLocation KWLoc, CXXScopeSpec &SS,
10316 IdentifierInfo *Name, SourceLocation NameLoc,
10317 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010318 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +000010319 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010320 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010321 SourceLocation ScopedEnumKWLoc,
10322 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010323 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010324 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +000010325 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +000010326 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000010327 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +000010328 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010329
Douglas Gregor402abb52009-05-28 23:31:59 +000010330 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010331 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +000010332 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +000010333
Douglas Gregor1fef4e62009-10-07 22:35:40 +000010334 // FIXME: Check explicit specializations more carefully.
10335 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010336 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +000010337
10338 // We only need to do this matching if we have template parameters
10339 // or a scope specifier, which also conveniently avoids this work
10340 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010341 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +000010342 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000010343 if (TemplateParameterList *TemplateParams =
10344 MatchTemplateParametersToScopeSpecifier(
10345 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10346 isExplicitSpecialization, Invalid)) {
Richard Smith725fe0e2013-04-01 21:43:41 +000010347 if (Kind == TTK_Enum) {
10348 Diag(KWLoc, diag::err_enum_template);
10349 return 0;
10350 }
10351
Douglas Gregord85bea22009-09-26 06:47:28 +000010352 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010353 // This is a declaration or definition of a class template (which may
10354 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010355
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010356 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +000010357 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010358
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010359 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +000010360 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010361 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010362 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010363 ModulePrivateLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010364 TemplateParameterLists.size()-1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010365 TemplateParameterLists.data());
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010366 return Result.get();
10367 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +000010368 // The "template<>" header is extraneous.
10369 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010370 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +000010371 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010372 }
Mike Stump1eb44332009-09-09 15:08:12 +000010373 }
10374 }
10375
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010376 // Figure out the underlying type if this a enum declaration. We need to do
10377 // this early, because it's needed to detect if this is an incompatible
10378 // redeclaration.
10379 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10380
10381 if (Kind == TTK_Enum) {
10382 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10383 // No underlying type explicitly specified, or we failed to parse the
10384 // type, default to int.
10385 EnumUnderlying = Context.IntTy.getTypePtr();
10386 else if (UnderlyingType.get()) {
10387 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10388 // integral type; any cv-qualification is ignored.
10389 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +000010390 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010391 EnumUnderlying = TI;
10392
Richard Smithf1c66b42012-03-14 23:13:10 +000010393 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010394 // Recover by falling back to int.
10395 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010396
Richard Smithf1c66b42012-03-14 23:13:10 +000010397 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010398 UPPC_FixedUnderlyingType))
10399 EnumUnderlying = Context.IntTy.getTypePtr();
10400
David Blaikie4e4d0842012-03-11 07:00:24 +000010401 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +000010402 // Microsoft enums are always of int type.
10403 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010404 }
10405
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010406 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010407 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010408 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010409
Chandler Carruth7bf36002010-03-01 21:17:36 +000010410 RedeclarationKind Redecl = ForRedeclaration;
10411 if (TUK == TUK_Friend || TUK == TUK_Reference)
10412 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +000010413
10414 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregord9433522013-06-27 20:42:30 +000010415 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010416 if (Name && SS.isNotEmpty()) {
10417 // We have a nested-name tag ('struct foo::bar').
10418
10419 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010420 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010421 Name = 0;
10422 goto CreateNewDecl;
10423 }
10424
John McCallc4e70192009-09-11 04:59:25 +000010425 // If this is a friend or a reference to a class in a dependent
10426 // context, don't try to make a decl for it.
10427 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10428 DC = computeDeclContext(SS, false);
10429 if (!DC) {
10430 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010431 return 0;
John McCallc4e70192009-09-11 04:59:25 +000010432 }
John McCall77bb1aa2010-05-01 00:40:08 +000010433 } else {
10434 DC = computeDeclContext(SS, true);
10435 if (!DC) {
10436 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10437 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +000010438 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +000010439 }
John McCallc4e70192009-09-11 04:59:25 +000010440 }
10441
John McCall77bb1aa2010-05-01 00:40:08 +000010442 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +000010443 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +000010444
Douglas Gregor1931b442009-02-03 00:34:39 +000010445 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010446 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +000010447 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +000010448
John McCall68263142009-11-18 22:49:29 +000010449 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010450 return 0;
John McCall6e247262009-10-10 05:48:19 +000010451
John McCall68263142009-11-18 22:49:29 +000010452 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010453 // Name lookup did not find anything. However, if the
10454 // nested-name-specifier refers to the current instantiation,
10455 // and that current instantiation has any dependent base
10456 // classes, we might find something at instantiation time: treat
10457 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +000010458 // But this only makes any sense for reference-like lookups.
10459 if (Previous.wasNotFoundInCurrentInstantiation() &&
10460 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010461 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010462 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010463 }
10464
10465 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +000010466 Diag(NameLoc, diag::err_not_tag_in_scope)
10467 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010468 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +000010469 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010470 goto CreateNewDecl;
10471 }
Chris Lattnercf79b012009-01-21 02:38:50 +000010472 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010473 // If this is a named struct, check to see if there was a previous forward
10474 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +000010475 // FIXME: We're looking into outer scopes here, even when we
10476 // shouldn't be. Doing so can result in ambiguities that we
10477 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +000010478 LookupName(Previous, S);
10479
John McCallc96cd7a2013-03-20 01:53:00 +000010480 // When declaring or defining a tag, ignore ambiguities introduced
10481 // by types using'ed into this scope.
Douglas Gregor93b6bce2011-05-09 21:46:33 +000010482 if (Previous.isAmbiguous() &&
10483 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +000010484 LookupResult::Filter F = Previous.makeFilter();
10485 while (F.hasNext()) {
10486 NamedDecl *ND = F.next();
10487 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10488 F.erase();
10489 }
10490 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +000010491 }
John McCallc96cd7a2013-03-20 01:53:00 +000010492
10493 // C++11 [namespace.memdef]p3:
10494 // If the name in a friend declaration is neither qualified nor
10495 // a template-id and the declaration is a function or an
10496 // elaborated-type-specifier, the lookup to determine whether
10497 // the entity has been previously declared shall not consider
10498 // any scopes outside the innermost enclosing namespace.
10499 //
10500 // Does it matter that this should be by scope instead of by
10501 // semantic context?
10502 if (!Previous.empty() && TUK == TUK_Friend) {
10503 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10504 LookupResult::Filter F = Previous.makeFilter();
10505 while (F.hasNext()) {
10506 NamedDecl *ND = F.next();
10507 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregord9433522013-06-27 20:42:30 +000010508 if (DC->isFileContext() &&
10509 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCallc96cd7a2013-03-20 01:53:00 +000010510 F.erase();
Douglas Gregord9433522013-06-27 20:42:30 +000010511 FriendSawTagOutsideEnclosingNamespace = true;
10512 }
John McCallc96cd7a2013-03-20 01:53:00 +000010513 }
10514 F.done();
10515 }
Douglas Gregor61c6c442011-05-04 00:25:33 +000010516
John McCall68263142009-11-18 22:49:29 +000010517 // Note: there used to be some attempt at recovery here.
10518 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010519 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +000010520
David Blaikie4e4d0842012-03-11 07:00:24 +000010521 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +000010522 // FIXME: This makes sure that we ignore the contexts associated
10523 // with C structs, unions, and enums when looking for a matching
10524 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +000010525 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010526 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10527 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +000010528 }
Douglas Gregor069ea642010-09-16 23:58:57 +000010529 } else if (S->isFunctionPrototypeScope()) {
10530 // If this is an enum declaration in function prototype scope, set its
10531 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +000010532 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +000010533 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010534 }
10535
John McCall68263142009-11-18 22:49:29 +000010536 if (Previous.isSingleResult() &&
10537 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010538 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +000010539 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +000010540 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +000010541 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +000010542 }
10543
David Blaikie4e4d0842012-03-11 07:00:24 +000010544 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010545 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010546 // This is a declaration of or a reference to "std::bad_alloc".
10547 isStdBadAlloc = true;
10548
John McCall68263142009-11-18 22:49:29 +000010549 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010550 // std::bad_alloc has been implicitly declared (but made invisible to
10551 // name lookup). Fill in this implicit declaration as the previous
10552 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010553 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010554 }
10555 }
John McCall68263142009-11-18 22:49:29 +000010556
John McCall9c86b512010-03-25 21:28:06 +000010557 // If we didn't find a previous declaration, and this is a reference
10558 // (or friend reference), move to the correct scope. In C++, we
10559 // also need to do a redeclaration lookup there, just in case
10560 // there's a shadow friend decl.
10561 if (Name && Previous.empty() &&
10562 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10563 if (Invalid) goto CreateNewDecl;
10564 assert(SS.isEmpty());
10565
10566 if (TUK == TUK_Reference) {
10567 // C++ [basic.scope.pdecl]p5:
10568 // -- for an elaborated-type-specifier of the form
10569 //
10570 // class-key identifier
10571 //
10572 // if the elaborated-type-specifier is used in the
10573 // decl-specifier-seq or parameter-declaration-clause of a
10574 // function defined in namespace scope, the identifier is
10575 // declared as a class-name in the namespace that contains
10576 // the declaration; otherwise, except as a friend
10577 // declaration, the identifier is declared in the smallest
10578 // non-class, non-function-prototype scope that contains the
10579 // declaration.
10580 //
10581 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10582 // C structs and unions.
10583 //
10584 // It is an error in C++ to declare (rather than define) an enum
10585 // type, including via an elaborated type specifier. We'll
10586 // diagnose that later; for now, declare the enum in the same
10587 // scope as we would have picked for any other tag type.
10588 //
10589 // GNU C also supports this behavior as part of its incomplete
10590 // enum types extension, while GNU C++ does not.
10591 //
10592 // Find the context where we'll be declaring the tag.
10593 // FIXME: We would like to maintain the current DeclContext as the
10594 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +000010595 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +000010596 SearchDC = SearchDC->getParent();
10597
10598 // Find the scope where we'll be declaring the tag.
10599 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010600 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +000010601 S->isFunctionPrototypeScope()) ||
10602 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +000010603 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCall9c86b512010-03-25 21:28:06 +000010604 S = S->getParent();
10605 } else {
10606 assert(TUK == TUK_Friend);
10607 // C++ [namespace.memdef]p3:
10608 // If a friend declaration in a non-local class first declares a
10609 // class or function, the friend class or function is a member of
10610 // the innermost enclosing namespace.
10611 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +000010612 }
10613
John McCall0d6b1642010-04-23 18:46:30 +000010614 // In C++, we need to do a redeclaration lookup to properly
10615 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +000010616 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +000010617 Previous.setRedeclarationKind(ForRedeclaration);
10618 LookupQualifiedName(Previous, SearchDC);
10619 }
10620 }
10621
John McCall68263142009-11-18 22:49:29 +000010622 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +000010623 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +000010624
10625 // It's okay to have a tag decl in the same scope as a typedef
10626 // which hides a tag decl in the same scope. Finding this
10627 // insanity with a redeclaration lookup can only actually happen
10628 // in C++.
10629 //
10630 // This is also okay for elaborated-type-specifiers, which is
10631 // technically forbidden by the current standard but which is
10632 // okay according to the likely resolution of an open issue;
10633 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +000010634 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +000010635 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +000010636 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10637 TagDecl *Tag = TT->getDecl();
10638 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010639 Tag->getDeclContext()->getRedeclContext()
10640 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +000010641 PrevDecl = Tag;
10642 Previous.clear();
10643 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +000010644 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +000010645 }
10646 }
10647 }
10648 }
10649
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010650 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010651 // If this is a use of a previous tag, or if the tag is already declared
10652 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010653 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +000010654 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +000010655 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010656 // Make sure that this wasn't declared as an enum and now used as a
10657 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +000010658 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10659 TUK == TUK_Definition, KWLoc,
10660 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +000010661 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010662 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10663 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +000010664 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +000010665 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +000010666 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +000010667 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10668 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +000010669 else
10670 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +000010671 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +000010672
Mike Stump1eb44332009-09-09 15:08:12 +000010673 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +000010674 Kind = PrevTagDecl->getTagKind();
10675 else {
10676 // Recover by making this an anonymous redefinition.
10677 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010678 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +000010679 Invalid = true;
10680 }
10681 }
10682
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010683 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10684 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10685
Richard Smithbdad7a22012-01-10 01:33:14 +000010686 // If this is an elaborated-type-specifier for a scoped enumeration,
10687 // the 'class' keyword is not necessary and not permitted.
10688 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10689 if (ScopedEnum)
10690 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10691 << PrevEnum->isScoped()
10692 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10693 return PrevTagDecl;
10694 }
10695
Richard Smithf1c66b42012-03-14 23:13:10 +000010696 QualType EnumUnderlyingTy;
10697 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10698 EnumUnderlyingTy = TI->getType();
10699 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10700 EnumUnderlyingTy = QualType(T, 0);
10701
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010702 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +000010703 // returning the previous declaration, unless this is a definition,
10704 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +000010705 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10706 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +000010707 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010708 }
10709
David Majnemer2ec2b842013-06-11 03:51:23 +000010710 // C++11 [class.mem]p1:
David Majnemer0f9b8552013-06-11 06:19:45 +000010711 // A member shall not be declared twice in the member-specification,
David Majnemer2ec2b842013-06-11 03:51:23 +000010712 // except that a nested class or member class template can be declared
10713 // and then later defined.
10714 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10715 S->isDeclScope(PrevDecl)) {
10716 Diag(NameLoc, diag::ext_member_redeclared);
10717 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10718 }
10719
Douglas Gregora3a83512009-04-01 23:51:29 +000010720 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010721 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +000010722
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010723 // FIXME: In the future, return a variant or some other clue
10724 // for the consumer of this Decl to know it doesn't own it.
10725 // For our current ASTs this shouldn't be a problem, but will
10726 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +000010727 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010728 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +000010729 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010730
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010731 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +000010732 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +000010733 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010734 // If we're defining a specialization and the previous definition
10735 // is from an implicit instantiation, don't emit an error
10736 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +000010737 bool IsExplicitSpecializationAfterInstantiation = false;
10738 if (isExplicitSpecialization) {
10739 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10740 IsExplicitSpecializationAfterInstantiation =
10741 RD->getTemplateSpecializationKind() !=
10742 TSK_ExplicitSpecialization;
10743 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10744 IsExplicitSpecializationAfterInstantiation =
10745 ED->getTemplateSpecializationKind() !=
10746 TSK_ExplicitSpecialization;
10747 }
10748
10749 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +000010750 // A redeclaration in function prototype scope in C isn't
10751 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +000010752 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +000010753 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10754 else
10755 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010756 Diag(Def->getLocation(), diag::note_previous_definition);
10757 // If this is a redefinition, recover by making this
10758 // struct be anonymous, which will make any later
10759 // references get the previous definition.
10760 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010761 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010762 Invalid = true;
10763 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010764 } else {
10765 // If the type is currently being defined, complain
10766 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +000010767 const TagType *Tag
10768 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010769 if (Tag->isBeingDefined()) {
10770 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +000010771 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010772 diag::note_previous_definition);
10773 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010774 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010775 Invalid = true;
10776 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010777 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010778
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010779 // Okay, this is definition of a previously declared or referenced
10780 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010781 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010782 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010783 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +000010784 // have a definition. Just create a new decl.
10785
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010786 } else {
10787 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +000010788 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010789 // new decl/type. We set PrevDecl to NULL so that the entities
10790 // have distinct types.
John McCall68263142009-11-18 22:49:29 +000010791 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010792 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010793 // If we get here, we're going to create a new Decl. If PrevDecl
10794 // is non-NULL, it's a definition of the tag declared by
10795 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +000010796
10797
10798 // Otherwise, PrevDecl is not a tag, but was found with tag
10799 // lookup. This is only actually possible in C++, where a few
10800 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010801 } else {
John McCall0d6b1642010-04-23 18:46:30 +000010802 // Use a better diagnostic if an elaborated-type-specifier
10803 // found the wrong kind of type on the first
10804 // (non-redeclaration) lookup.
10805 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10806 !Previous.isForRedeclaration()) {
10807 unsigned Kind = 0;
10808 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010809 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10810 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010811 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10812 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10813 Invalid = true;
10814
10815 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +000010816 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10817 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +000010818 // do nothing
10819
10820 // Diagnose implicit declarations introduced by elaborated types.
10821 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10822 unsigned Kind = 0;
10823 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010824 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10825 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010826 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10827 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10828 Invalid = true;
10829
10830 // Otherwise it's a declaration. Call out a particularly common
10831 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +000010832 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10833 unsigned Kind = 0;
10834 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +000010835 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +000010836 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +000010837 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10838 Invalid = true;
10839
10840 // Otherwise, diagnose.
10841 } else {
10842 // The tag name clashes with something else in the target scope,
10843 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +000010844 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010845 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010846 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010847 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010848 }
John McCall0d6b1642010-04-23 18:46:30 +000010849
10850 // The existing declaration isn't relevant to us; we're in a
10851 // new scope, so clear out the previous declaration.
10852 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010853 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010854 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000010855
Chris Lattnercc98eac2008-12-17 07:13:27 +000010856CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +000010857
John McCall68263142009-11-18 22:49:29 +000010858 TagDecl *PrevDecl = 0;
10859 if (Previous.isSingleResult())
10860 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10861
Reid Spencer5f016e22007-07-11 17:01:13 +000010862 // If there is an identifier, use the location of the identifier as the
10863 // location of the decl, otherwise use the location of the struct/union
10864 // keyword.
10865 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000010866
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010867 // Otherwise, create a new declaration. If there is a previous
10868 // declaration of the same entity, the two will be linked via
10869 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +000010870 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +000010871
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010872 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010873 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010874 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10875 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010876 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010877 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010878 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +000010879 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010880 if (TUK != TUK_Definition && !Invalid) {
10881 TagDecl *Def;
Douglas Gregorabde2c72013-03-25 22:22:35 +000010882 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10883 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010884 // C++0x: 7.2p2: opaque-enum-declaration.
10885 // Conflicts are diagnosed above. Do nothing.
10886 }
10887 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010888 Diag(Loc, diag::ext_forward_ref_enum_def)
10889 << New;
10890 Diag(Def->getLocation(), diag::note_previous_definition);
10891 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010892 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010893 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010894 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010895 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010896 DiagID = diag::err_forward_ref_enum;
10897 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010898
10899 // If this is a forward-declared reference to an enumeration, make a
10900 // note of it; we won't actually be introducing the declaration into
10901 // the declaration context.
10902 if (TUK == TUK_Reference)
10903 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010904 }
Douglas Gregor80711a22009-03-06 18:34:03 +000010905 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010906
10907 if (EnumUnderlying) {
10908 EnumDecl *ED = cast<EnumDecl>(New);
10909 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10910 ED->setIntegerTypeSourceInfo(TI);
10911 else
10912 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10913 ED->setPromotionType(ED->getIntegerType());
10914 }
10915
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000010916 } else {
10917 // struct/union/class
10918
Reid Spencer5f016e22007-07-11 17:01:13 +000010919 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10920 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +000010921 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +000010922 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010923 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010924 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010925
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010926 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010927 StdBadAlloc = cast<CXXRecordDecl>(New);
10928 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010929 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010930 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000010931 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010932
John McCallb6217662010-03-15 10:12:16 +000010933 // Maybe add qualifier info.
10934 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010935 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +000010936 // If this is either a declaration or a definition, check the
10937 // nested-name-specifier against the current context. We don't do this
10938 // for explicit specializations, because they have similar checking
10939 // (with more specific diagnostics) in the call to
10940 // CheckMemberSpecialization, below.
10941 if (!isExplicitSpecialization &&
10942 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10943 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10944 Invalid = true;
10945
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000010946 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010947 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +000010948 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010949 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010950 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +000010951 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010952 }
10953 else
10954 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +000010955 }
10956
Daniel Dunbar9f21f892010-05-27 01:53:40 +000010957 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10958 // Add alignment attributes if necessary; these attributes are checked when
10959 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010960 //
10961 // It is important for implementing the correct semantics that this
10962 // happen here (in act on tag decl). The #pragma pack stack is
10963 // maintained as a result of parser callbacks which can occur at
10964 // many points during the parsing of a struct declaration (because
10965 // the #pragma tokens are effectively skipped over during the
10966 // parsing of the struct).
Eli Friedman2016c8c2012-08-08 21:08:34 +000010967 if (TUK == TUK_Definition) {
10968 AddAlignmentAttributesForRecord(RD);
10969 AddMsStructLayoutForRecord(RD);
10970 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010971 }
10972
Douglas Gregor2ccd89c2011-12-20 18:11:52 +000010973 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +000010974 if (isExplicitSpecialization)
10975 Diag(New->getLocation(), diag::err_module_private_specialization)
10976 << 2
10977 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +000010978 // __module_private__ does not apply to local classes. However, we only
10979 // diagnose this as an error when the declaration specifiers are
10980 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +000010981 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +000010982 New->setModulePrivate();
10983 }
10984
Douglas Gregorf6b11852009-10-08 15:14:33 +000010985 // If this is a specialization of a member class (of a class template),
10986 // check the specialization.
John McCall68263142009-11-18 22:49:29 +000010987 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +000010988 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +000010989
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010990 if (Invalid)
10991 New->setInvalidDecl();
10992
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010993 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010994 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010995
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010996 // If we're declaring or defining a tag in function prototype scope
10997 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +000010998 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +000010999 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11000
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000011001 // Set the lexical context. If the tag has a C++ scope specifier, the
11002 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +000011003 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011004
John McCall02cace72009-08-28 07:59:38 +000011005 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +000011006 // In Microsoft mode, a friend declaration also acts as a forward
11007 // declaration so we always pass true to setObjectOfFriendDecl to make
11008 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +000011009 if (TUK == TUK_Friend)
Richard Smith22050f22013-07-17 23:53:16 +000011010 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11011 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +000011012
Anders Carlsson0cf88302009-03-26 01:19:02 +000011013 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +000011014 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +000011015 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +000011016
John McCall0f434ec2009-07-31 02:45:11 +000011017 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011018 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +000011019
Reid Spencer5f016e22007-07-11 17:01:13 +000011020 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +000011021 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +000011022 // We might be replacing an existing declaration in the lookup tables;
11023 // if so, borrow its access specifier.
11024 if (PrevDecl)
11025 New->setAccess(PrevDecl->getAccess());
11026
Sebastian Redl7a126a42010-08-31 00:36:30 +000011027 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011028 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +000011029 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +000011030 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11031 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +000011032 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000011033 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011034 PushOnScopeChains(New, S, !IsForwardReference);
11035 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011036 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011037
Douglas Gregor4920f1f2009-01-12 22:49:06 +000011038 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011039 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +000011040 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000011041
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011042 // If this is the C FILE type, notify the AST context.
11043 if (IdentifierInfo *II = New->getIdentifier())
11044 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000011045 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011046 II->isStr("FILE"))
11047 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +000011048
James Molloy16f1f712012-02-29 10:24:19 +000011049 // If we were in function prototype scope (and not in C++ mode), add this
11050 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +000011051 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +000011052 InFunctionDeclarator && Name)
11053 DeclsInPrototypeScope.push_back(New);
11054
Rafael Espindola98ae8342012-05-10 02:50:16 +000011055 if (PrevDecl)
11056 mergeDeclAttributes(New, PrevDecl);
11057
Rafael Espindola71adc5b2012-07-17 15:14:47 +000011058 // If there's a #pragma GCC visibility in scope, set the visibility of this
11059 // record.
11060 AddPushedVisibilityAttribute(New);
11061
Douglas Gregor402abb52009-05-28 23:31:59 +000011062 OwnedDecl = true;
Richard Smith37ec8d52012-12-05 11:34:06 +000011063 // In C++, don't return an invalid declaration. We can't recover well from
11064 // the cases where we make the type anonymous.
11065 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Reid Spencer5f016e22007-07-11 17:01:13 +000011066}
11067
John McCalld226f652010-08-21 09:40:31 +000011068void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011069 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011070 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +000011071
Douglas Gregor72de6672009-01-08 20:45:30 +000011072 // Enter the tag context.
11073 PushDeclContext(S, Tag);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000011074
11075 ActOnDocumentableDecl(TagD);
Rafael Espindola5e065292012-07-12 04:47:34 +000011076
11077 // If there's a #pragma GCC visibility in scope, set the visibility of this
11078 // record.
11079 AddPushedVisibilityAttribute(Tag);
John McCallf9368152009-12-20 07:58:13 +000011080}
Douglas Gregor72de6672009-01-08 20:45:30 +000011081
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011082Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011083 assert(isa<ObjCContainerDecl>(IDecl) &&
11084 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11085 DeclContext *OCD = cast<DeclContext>(IDecl);
11086 assert(getContainingDC(OCD) == CurContext &&
11087 "The next DeclContext should be lexically contained in the current one.");
11088 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011089 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011090}
11091
John McCalld226f652010-08-21 09:40:31 +000011092void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011093 SourceLocation FinalLoc,
David Majnemer7121bdb2013-10-18 00:33:31 +000011094 bool IsFinalSpelledSealed,
John McCallf9368152009-12-20 07:58:13 +000011095 SourceLocation LBraceLoc) {
11096 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011097 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +000011098
John McCallf9368152009-12-20 07:58:13 +000011099 FieldCollector->StartClass();
11100
11101 if (!Record->getIdentifier())
11102 return;
11103
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011104 if (FinalLoc.isValid())
David Majnemer7121bdb2013-10-18 00:33:31 +000011105 Record->addAttr(new (Context)
11106 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11107
John McCallf9368152009-12-20 07:58:13 +000011108 // C++ [class]p2:
11109 // [...] The class-name is also inserted into the scope of the
11110 // class itself; this is known as the injected-class-name. For
11111 // purposes of access checking, the injected-class-name is treated
11112 // as if it were a public member name.
11113 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000011114 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11115 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +000011116 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +000011117 /*PrevDecl=*/0,
11118 /*DelayTypeCreation=*/true);
11119 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +000011120 InjectedClassName->setImplicit();
11121 InjectedClassName->setAccess(AS_public);
11122 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11123 InjectedClassName->setDescribedClassTemplate(Template);
11124 PushOnScopeChains(InjectedClassName, S);
11125 assert(InjectedClassName->isInjectedClassName() &&
11126 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +000011127}
11128
John McCalld226f652010-08-21 09:40:31 +000011129void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011130 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011131 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011132 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011133 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +000011134
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011135 // Make sure we "complete" the definition even it is invalid.
11136 if (Tag->isBeingDefined()) {
11137 assert(Tag->isInvalidDecl() && "We should already have completed it");
11138 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11139 RD->completeDefinition();
11140 }
11141
Douglas Gregor72de6672009-01-08 20:45:30 +000011142 if (isa<CXXRecordDecl>(Tag))
11143 FieldCollector->FinishClass();
11144
11145 // Exit this scope of this tag's definition.
11146 PopDeclContext();
Argyrios Kyrtzidis3d207e72013-01-29 18:00:54 +000011147
11148 if (getCurLexicalContext()->isObjCContainer() &&
11149 Tag->getDeclContext()->isFileContext())
11150 Tag->setTopLevelDeclInObjCContainer();
11151
Douglas Gregor72de6672009-01-08 20:45:30 +000011152 // Notify the consumer that we've defined a tag.
Serge Pavlov439b7012013-07-02 17:31:56 +000011153 if (!Tag->isInvalidDecl())
11154 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor72de6672009-01-08 20:45:30 +000011155}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +000011156
Fariborz Jahanian10af8792011-08-29 17:33:12 +000011157void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011158 // Exit this scope of this interface definition.
11159 PopDeclContext();
11160}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011161
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011162void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +000011163 assert(DC == CurContext && "Mismatch of container contexts");
11164 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011165 ActOnObjCContainerFinishDefinition();
11166}
11167
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011168void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11169 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011170 OriginalLexicalContext = 0;
11171}
11172
John McCalld226f652010-08-21 09:40:31 +000011173void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +000011174 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011175 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +000011176 Tag->setInvalidDecl();
11177
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011178 // Make sure we "complete" the definition even it is invalid.
11179 if (Tag->isBeingDefined()) {
11180 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11181 RD->completeDefinition();
11182 }
11183
John McCalla8cab012010-03-17 19:25:57 +000011184 // We're undoing ActOnTagStartDefinition here, not
11185 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11186 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +000011187
11188 PopDeclContext();
11189}
11190
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011191// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +000011192ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11193 IdentifierInfo *FieldName,
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011194 QualType FieldTy, bool IsMsStruct,
11195 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +000011196 // Default to true; that shouldn't confuse checks for emptiness
11197 if (ZeroWidth)
11198 *ZeroWidth = true;
11199
Chris Lattner24793662009-03-05 22:45:59 +000011200 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +000011201 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000011202 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +000011203 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +000011204 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +000011205 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011206 if (FieldName)
11207 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11208 << FieldName << FieldTy << BitWidth->getSourceRange();
11209 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11210 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +000011211 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11212 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +000011213 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011214
11215 // If the bit-width is type- or value-dependent, don't try to check
11216 // it now.
11217 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +000011218 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011219
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011220 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +000011221 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11222 if (ICE.isInvalid())
11223 return ICE;
11224 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011225
Eli Friedman1d954f62009-08-15 21:55:26 +000011226 if (Value != 0 && ZeroWidth)
11227 *ZeroWidth = false;
11228
Chris Lattnercd087072008-12-12 04:56:04 +000011229 // Zero-width bitfield is ok for anonymous field.
11230 if (Value == 0 && FieldName)
11231 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +000011232
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011233 if (Value.isSigned() && Value.isNegative()) {
11234 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +000011235 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011236 << FieldName << Value.toString(10);
11237 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11238 << Value.toString(10);
11239 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011240
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011241 if (!FieldTy->isDependentType()) {
11242 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011243 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011244 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlsson72468ec2010-04-16 15:16:32 +000011245 if (FieldName)
11246 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11247 << FieldName << (unsigned)Value.getZExtValue()
11248 << (unsigned)TypeSize;
11249
11250 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11251 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11252 }
11253
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011254 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +000011255 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11256 << FieldName << (unsigned)Value.getZExtValue()
11257 << (unsigned)TypeSize;
11258 else
11259 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11260 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011261 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011262 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011263
Richard Smith282e7e62012-02-04 09:53:13 +000011264 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011265}
11266
Richard Smith7a614d82011-06-11 17:19:42 +000011267/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +000011268/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +000011269Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011270 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +000011271 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +000011272 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smithca523302012-06-10 03:12:00 +000011273 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCalld226f652010-08-21 09:40:31 +000011274 return Res;
Chris Lattner24793662009-03-05 22:45:59 +000011275}
11276
11277/// HandleField - Analyze a field of a C struct or a C++ data member.
11278///
11279FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11280 SourceLocation DeclStart,
Richard Smithca523302012-06-10 03:12:00 +000011281 Declarator &D, Expr *BitWidth,
11282 InClassInitStyle InitStyle,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011283 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011284 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +000011285 SourceLocation Loc = DeclStart;
11286 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011287
John McCallbf1a0282010-06-04 23:28:52 +000011288 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11289 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +000011290 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011291 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +000011292
Douglas Gregore1862692010-12-15 23:18:36 +000011293 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11294 UPPC_DataMemberType)) {
11295 D.setInvalidType();
11296 T = Context.IntTy;
11297 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11298 }
11299 }
11300
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011301 // TR 18037 does not allow fields to be declared with address spaces.
11302 if (T.getQualifiers().hasAddressSpace()) {
11303 Diag(Loc, diag::err_field_with_address_space);
11304 D.setInvalidType();
11305 }
11306
Guy Benyeie6b9d802013-01-20 12:31:11 +000011307 // OpenCL 1.2 spec, s6.9 r:
11308 // The event type cannot be used to declare a structure or union field.
11309 if (LangOpts.OpenCL && T->isEventT()) {
11310 Diag(Loc, diag::err_event_t_struct_field);
11311 D.setInvalidType();
11312 }
11313
Richard Smithc7f81162013-03-18 22:52:47 +000011314 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +000011315
Richard Smithec642442013-04-12 22:46:28 +000011316 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11317 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11318 diag::err_invalid_thread)
11319 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011320
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011321 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +000011322 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011323 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11324 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +000011325 switch (Previous.getResultKind()) {
11326 case LookupResult::Found:
11327 case LookupResult::FoundUnresolvedValue:
11328 PrevDecl = Previous.getAsSingle<NamedDecl>();
11329 break;
11330
11331 case LookupResult::FoundOverloaded:
11332 PrevDecl = Previous.getRepresentativeDecl();
11333 break;
11334
11335 case LookupResult::NotFound:
11336 case LookupResult::NotFoundInCurrentInstantiation:
11337 case LookupResult::Ambiguous:
11338 break;
11339 }
11340 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +000011341
11342 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11343 // Maybe we will complain about the shadowed template parameter.
11344 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11345 // Just pretend that we didn't see the previous declaration.
11346 PrevDecl = 0;
11347 }
11348
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011349 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11350 PrevDecl = 0;
11351
Steve Naroffea218b82009-07-14 14:58:18 +000011352 bool Mutable
11353 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +000011354 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +000011355 FieldDecl *NewFD
Richard Smithca523302012-06-10 03:12:00 +000011356 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith7a614d82011-06-11 17:19:42 +000011357 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +000011358
11359 if (NewFD->isInvalidDecl())
11360 Record->setInvalidDecl();
11361
Douglas Gregor591dc842011-09-12 16:11:24 +000011362 if (D.getDeclSpec().isModulePrivateSpecified())
11363 NewFD->setModulePrivate();
11364
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011365 if (NewFD->isInvalidDecl() && PrevDecl) {
11366 // Don't introduce NewFD into scope; there's already something
11367 // with the same name in the same scope.
11368 } else if (II) {
11369 PushOnScopeChains(NewFD, S);
11370 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011371 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011372
11373 return NewFD;
11374}
11375
11376/// \brief Build a new FieldDecl and check its well-formedness.
11377///
11378/// This routine builds a new FieldDecl given the fields name, type,
11379/// record, etc. \p PrevDecl should refer to any previous declaration
11380/// with the same name and in the same scope as the field to be
11381/// created.
11382///
11383/// \returns a new FieldDecl.
11384///
Mike Stump1eb44332009-09-09 15:08:12 +000011385/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +000011386FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000011387 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011388 RecordDecl *Record, SourceLocation Loc,
Richard Smithca523302012-06-10 03:12:00 +000011389 bool Mutable, Expr *BitWidth,
11390 InClassInitStyle InitStyle,
Steve Naroffea218b82009-07-14 14:58:18 +000011391 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011392 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011393 Declarator *D) {
11394 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +000011395 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +000011396 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +000011397
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011398 // If we receive a broken type, recover by assuming 'int' and
11399 // marking this declaration as invalid.
11400 if (T.isNull()) {
11401 InvalidDecl = true;
11402 T = Context.IntTy;
11403 }
11404
Eli Friedman721e77d2009-12-07 00:22:08 +000011405 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011406 if (!EltTy->isDependentType()) {
11407 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11408 // Fields of incomplete type force their record to be invalid.
11409 Record->setInvalidDecl();
11410 InvalidDecl = true;
11411 } else {
11412 NamedDecl *Def;
11413 EltTy->isIncompleteType(&Def);
11414 if (Def && Def->isInvalidDecl()) {
11415 Record->setInvalidDecl();
11416 InvalidDecl = true;
11417 }
11418 }
John McCall2d7d2d92010-08-16 23:42:35 +000011419 }
Eli Friedman721e77d2009-12-07 00:22:08 +000011420
Joey Gouly617bb312013-01-17 17:35:00 +000011421 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11422 if (BitWidth && getLangOpts().OpenCL) {
11423 Diag(Loc, diag::err_opencl_bitfields);
11424 InvalidDecl = true;
11425 }
11426
Reid Spencer5f016e22007-07-11 17:01:13 +000011427 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11428 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +000011429 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011430 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +000011431 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011432
11433 TypeSourceInfo *FixedTInfo =
11434 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11435 SizeIsNegative,
11436 Oversized);
11437 if (FixedTInfo) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011438 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011439 TInfo = FixedTInfo;
11440 T = FixedTInfo->getType();
Eli Friedman1ca48132009-02-21 00:44:51 +000011441 } else {
11442 if (SizeIsNegative)
11443 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +000011444 else if (Oversized.getBoolValue())
11445 Diag(Loc, diag::err_array_too_large)
11446 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +000011447 else
11448 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +000011449 InvalidDecl = true;
11450 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011451 }
Mike Stump1eb44332009-09-09 15:08:12 +000011452
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011453 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +000011454 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11455 diag::err_abstract_type_in_decl,
11456 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011457 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +000011458
Eli Friedman1d954f62009-08-15 21:55:26 +000011459 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011460 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +000011461 if (!InvalidDecl && BitWidth) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011462 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11463 &ZeroWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011464 if (!BitWidth) {
11465 InvalidDecl = true;
11466 BitWidth = 0;
11467 ZeroWidth = false;
11468 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011469 }
Mike Stump1eb44332009-09-09 15:08:12 +000011470
John McCall4bde1e12010-06-04 08:34:12 +000011471 // Check that 'mutable' is consistent with the type of the declaration.
11472 if (!InvalidDecl && Mutable) {
11473 unsigned DiagID = 0;
11474 if (T->isReferenceType())
11475 DiagID = diag::err_mutable_reference;
11476 else if (T.isConstQualified())
11477 DiagID = diag::err_mutable_const;
11478
11479 if (DiagID) {
11480 SourceLocation ErrLoc = Loc;
11481 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11482 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11483 Diag(ErrLoc, DiagID);
11484 Mutable = false;
11485 InvalidDecl = true;
11486 }
11487 }
11488
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011489 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +000011490 BitWidth, Mutable, InitStyle);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011491 if (InvalidDecl)
11492 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +000011493
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011494 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11495 Diag(Loc, diag::err_duplicate_member) << II;
11496 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11497 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +000011498 }
11499
David Blaikie4e4d0842012-03-11 07:00:24 +000011500 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +000011501 if (Record->isUnion()) {
11502 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11503 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11504 if (RDecl->getDefinition()) {
11505 // C++ [class.union]p1: An object of a class with a non-trivial
11506 // constructor, a non-trivial copy constructor, a non-trivial
11507 // destructor, or a non-trivial copy assignment operator
11508 // cannot be a member of a union, nor can an array of such
11509 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +000011510 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +000011511 NewFD->setInvalidDecl();
11512 }
11513 }
11514
11515 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballman76eed422013-05-30 16:20:00 +000011516 // the program is ill-formed, except when compiling with MSVC extensions
11517 // enabled.
Anders Carlssondfdfc582010-11-07 19:13:55 +000011518 if (EltTy->isReferenceType()) {
Aaron Ballman76eed422013-05-30 16:20:00 +000011519 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11520 diag::ext_union_member_of_reference_type :
11521 diag::err_union_member_of_reference_type)
Anders Carlssondfdfc582010-11-07 19:13:55 +000011522 << NewFD->getDeclName() << EltTy;
Aaron Ballman76eed422013-05-30 16:20:00 +000011523 if (!getLangOpts().MicrosoftExt)
11524 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +000011525 }
11526 }
11527 }
11528
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011529 // FIXME: We need to pass in the attributes given an AST
11530 // representation, not a parser representation.
Richard Smithbe507b62013-02-01 08:12:08 +000011531 if (D) {
Douglas Gregor92eb7d82013-05-02 23:25:32 +000011532 // FIXME: The current scope is almost... but not entirely... correct here.
11533 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011534
Richard Smithbe507b62013-02-01 08:12:08 +000011535 if (NewFD->hasAttrs())
11536 CheckAlignasUnderalignment(NewFD);
11537 }
11538
John McCallf85e1932011-06-15 23:02:42 +000011539 // In auto-retain/release, infer strong retension for fields of
11540 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011541 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +000011542 NewFD->setInvalidDecl();
11543
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +000011544 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +000011545 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +000011546
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011547 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +000011548 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +000011549}
11550
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011551bool Sema::CheckNontrivialField(FieldDecl *FD) {
11552 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +000011553 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011554
Nick Lewyckydccd04d2013-06-25 23:22:23 +000011555 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11556 return false;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011557
11558 QualType EltTy = Context.getBaseElementType(FD->getType());
11559 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smithac713512012-12-08 02:53:02 +000011560 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011561 if (RDecl->getDefinition()) {
11562 // We check for copy constructors before constructors
11563 // because otherwise we'll never get complaints about
11564 // copy constructors.
11565
11566 CXXSpecialMember member = CXXInvalid;
Richard Smith426391c2012-11-16 00:53:38 +000011567 // We're required to check for any non-trivial constructors. Since the
11568 // implicit default constructor is suppressed if there are any
11569 // user-declared constructors, we just need to check that there is a
11570 // trivial default constructor and a trivial copy constructor. (We don't
11571 // worry about move constructors here, since this is a C++98 check.)
11572 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011573 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +000011574 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +000011575 member = CXXDefaultConstructor;
Richard Smith426391c2012-11-16 00:53:38 +000011576 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011577 member = CXXCopyAssignment;
Richard Smith426391c2012-11-16 00:53:38 +000011578 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011579 member = CXXDestructor;
11580
11581 if (member != CXXInvalid) {
Richard Smith80ad52f2013-01-02 11:42:31 +000011582 if (!getLangOpts().CPlusPlus11 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011583 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +000011584 // Objective-C++ ARC: it is an error to have a non-trivial field of
11585 // a union. However, system headers in Objective-C programs
11586 // occasionally have Objective-C lifetime objects within unions,
11587 // and rather than cause the program to fail, we make those
11588 // members unavailable.
11589 SourceLocation Loc = FD->getLocation();
11590 if (getSourceManager().isInSystemHeader(Loc)) {
11591 if (!FD->hasAttr<UnavailableAttr>())
11592 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011593 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011594 return false;
11595 }
11596 }
Richard Smithe7d7c392011-10-19 20:41:51 +000011597
Richard Smith80ad52f2013-01-02 11:42:31 +000011598 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithe7d7c392011-10-19 20:41:51 +000011599 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11600 diag::err_illegal_union_or_anon_struct_member)
11601 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smithac713512012-12-08 02:53:02 +000011602 DiagnoseNontrivial(RDecl, member);
Richard Smith80ad52f2013-01-02 11:42:31 +000011603 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011604 }
11605 }
11606 }
Richard Smithac713512012-12-08 02:53:02 +000011607
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011608 return false;
11609}
11610
Mike Stump1eb44332009-09-09 15:08:12 +000011611/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011612/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011613static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011614TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +000011615 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +000011616 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +000011617 case tok::objc_private: return ObjCIvarDecl::Private;
11618 case tok::objc_public: return ObjCIvarDecl::Public;
11619 case tok::objc_protected: return ObjCIvarDecl::Protected;
11620 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +000011621 }
11622}
11623
Mike Stump1eb44332009-09-09 15:08:12 +000011624/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +000011625/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +000011626Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +000011627 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011628 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +000011629 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +000011630
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011631 IdentifierInfo *II = D.getIdentifier();
11632 Expr *BitWidth = (Expr*)BitfieldWidth;
11633 SourceLocation Loc = DeclStart;
11634 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011635
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011636 // FIXME: Unnamed fields can be handled in various different ways, for
11637 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +000011638
John McCallbf1a0282010-06-04 23:28:52 +000011639 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11640 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000011641
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011642 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +000011643 // 6.7.2.1p3, 6.7.2.1p4
Warren Huntb2969b12013-10-11 20:19:00 +000011644 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011645 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +000011646 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011647 } else {
11648 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +000011649
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011650 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +000011651
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011652 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011653 if (T->isReferenceType()) {
11654 Diag(Loc, diag::err_ivar_reference_type);
11655 D.setInvalidType();
11656 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011657 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11658 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011659 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +000011660 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011661 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011662 }
Mike Stump1eb44332009-09-09 15:08:12 +000011663
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011664 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +000011665 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011666 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11667 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011668 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011669 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +000011670 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11671 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +000011672 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +000011673 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011674 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011675 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011676 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +000011677 EnclosingContext = IMPDecl->getClassInterface();
11678 assert(EnclosingContext && "Implementation has no class interface!");
11679 }
11680 else
11681 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011682 } else {
11683 if (ObjCCategoryDecl *CDecl =
11684 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011685 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011686 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +000011687 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011688 }
11689 }
Daniel Dunbara19331f2010-04-02 18:29:09 +000011690 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011691 }
Mike Stump1eb44332009-09-09 15:08:12 +000011692
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011693 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011694 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11695 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +000011696 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +000011697
Douglas Gregor72de6672009-01-08 20:45:30 +000011698 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000011699 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +000011700 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011701 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +000011702 && !isa<TagDecl>(PrevDecl)) {
11703 Diag(Loc, diag::err_duplicate_member) << II;
11704 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11705 NewID->setInvalidDecl();
11706 }
11707 }
11708
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011709 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011710 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +000011711
Chris Lattnereaaebc72009-04-25 08:06:05 +000011712 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011713 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011714
John McCallf85e1932011-06-15 23:02:42 +000011715 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011716 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +000011717 NewID->setInvalidDecl();
11718
Douglas Gregor591dc842011-09-12 16:11:24 +000011719 if (D.getDeclSpec().isModulePrivateSpecified())
11720 NewID->setModulePrivate();
11721
Douglas Gregor72de6672009-01-08 20:45:30 +000011722 if (II) {
11723 // FIXME: When interfaces are DeclContexts, we'll need to add
11724 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +000011725 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +000011726 IdResolver.AddDecl(NewID);
11727 }
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011728
John McCall260611a2012-06-20 06:18:46 +000011729 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011730 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniandc3eb6a2012-05-15 17:43:16 +000011731 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011732
John McCalld226f652010-08-21 09:40:31 +000011733 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011734}
11735
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011736/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosed4582b82013-04-03 01:39:23 +000011737/// class and class extensions. For every class \@interface and class
11738/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011739/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011740void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011741 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall260611a2012-06-20 06:18:46 +000011742 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011743 return;
11744
11745 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11746 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11747
Richard Smitha6b8b2c2011-10-10 18:28:20 +000011748 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011749 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011750 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011751 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011752 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011753 if (!CD->IsClassExtension())
11754 return;
11755 }
11756 // No need to add this to end of @implementation.
11757 else
11758 return;
11759 }
11760 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011761 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11762 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011763
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011764 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011765 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011766 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011767 Context.getTrivialTypeSourceInfo(Context.CharTy,
11768 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011769 ObjCIvarDecl::Private, BW,
11770 true);
11771 AllIvarDecls.push_back(Ivar);
11772}
11773
Robert Wilhelm834c0582013-08-09 18:02:13 +000011774void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11775 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11776 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +000011777 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +000011778
Eric Christopher6dba4a12012-07-19 22:22:51 +000011779 // If this is an Objective-C @implementation or category and we have
11780 // new fields here we should reset the layout of the interface since
11781 // it will now change.
11782 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11783 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11784 switch (DC->getKind()) {
11785 default: break;
11786 case Decl::ObjCCategory:
11787 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11788 break;
11789 case Decl::ObjCImplementation:
11790 Context.
11791 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11792 break;
11793 }
11794 }
11795
Eli Friedman11e70d72012-02-07 05:00:47 +000011796 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11797
11798 // Start counting up the number of named members; make sure to include
11799 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +000011800 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +000011801 if (Record) {
11802 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11803 e = Record->decls_end(); i != e; i++) {
11804 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11805 if (IFD->getDeclName())
11806 ++NumNamedMembers;
11807 }
11808 }
11809
11810 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011811 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011812
John McCallf85e1932011-06-15 23:02:42 +000011813 bool ARCErrReported = false;
Robert Wilhelm834c0582013-08-09 18:02:13 +000011814 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie77b6de02011-09-22 02:58:26 +000011815 i != end; ++i) {
11816 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +000011817
Reid Spencer5f016e22007-07-11 17:01:13 +000011818 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +000011819 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011820
Douglas Gregor72de6672009-01-08 20:45:30 +000011821 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011822 // Remember all fields written by the user.
11823 RecFields.push_back(FD);
11824 }
Mike Stump1eb44332009-09-09 15:08:12 +000011825
Chris Lattner24793662009-03-05 22:45:59 +000011826 // If the field is already invalid for some reason, don't emit more
11827 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +000011828 if (FD->isInvalidDecl()) {
11829 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +000011830 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +000011831 }
Mike Stump1eb44332009-09-09 15:08:12 +000011832
Douglas Gregore7450f52009-03-24 19:52:54 +000011833 // C99 6.7.2.1p2:
11834 // A structure or union shall not contain a member with
11835 // incomplete or function type (hence, a structure shall not
11836 // contain an instance of itself, but may contain a pointer to
11837 // an instance of itself), except that the last member of a
11838 // structure with more than one named member may have incomplete
11839 // array type; such a structure (and any union containing,
11840 // possibly recursively, a member that is such a structure)
11841 // shall not be a member of a structure or an element of an
11842 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +000011843 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011844 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011845 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011846 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011847 FD->setInvalidDecl();
11848 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011849 continue;
Francois Pichet09246182010-09-15 00:14:08 +000011850 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +000011851 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +000011852 ((getLangOpts().MicrosoftExt ||
11853 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +000011854 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011855 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011856 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +000011857 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +000011858 // as the sole element of a struct/class.
David Majnemer633c0c22013-11-02 10:38:05 +000011859 unsigned DiagID = 0;
11860 if (Record->isUnion())
11861 DiagID = getLangOpts().MicrosoftExt
11862 ? diag::ext_flexible_array_union_ms
11863 : getLangOpts().CPlusPlus
11864 ? diag::ext_flexible_array_union_gnu
11865 : diag::err_flexible_array_union;
11866 else if (Fields.size() == 1)
11867 DiagID = getLangOpts().MicrosoftExt
11868 ? diag::ext_flexible_array_empty_aggregate_ms
11869 : getLangOpts().CPlusPlus
11870 ? diag::ext_flexible_array_empty_aggregate_gnu
11871 : NumNamedMembers < 1
11872 ? diag::err_flexible_array_empty_aggregate
11873 : 0;
11874
11875 if (DiagID)
11876 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11877 << Record->getTagKind();
David Majnemer3a665572013-11-02 11:19:13 +000011878 // While the layout of types that contain virtual bases is not specified
11879 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11880 // virtual bases after the derived members. This would make a flexible
11881 // array member declared at the end of an object not adjacent to the end
11882 // of the type.
11883 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11884 if (RD->getNumVBases() != 0)
11885 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11886 << FD->getDeclName() << Record->getTagKind();
David Majnemer633c0c22013-11-02 10:38:05 +000011887 if (!getLangOpts().C99)
11888 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11889 << FD->getDeclName() << Record->getTagKind();
11890
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011891 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +000011892 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011893 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +000011894 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011895 FD->setInvalidDecl();
11896 EnclosingDecl->setInvalidDecl();
11897 continue;
11898 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011899 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +000011900 if (Record)
11901 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +000011902 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +000011903 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +000011904 diag::err_field_incomplete)) {
11905 // Incomplete type
11906 FD->setInvalidDecl();
11907 EnclosingDecl->setInvalidDecl();
11908 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +000011909 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011910 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11911 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000011912 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011913 Record->setHasFlexibleArrayMember(true);
11914 } else {
11915 // If this is a struct/class and this is not the last element, reject
11916 // it. Note that GCC supports variable sized arrays in the middle of
11917 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +000011918 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +000011919 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +000011920 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +000011921 else {
11922 // We support flexible arrays at the end of structs in
11923 // other structs as an extension.
11924 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11925 << FD->getDeclName();
11926 if (Record)
11927 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011928 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011929 }
11930 }
Fariborz Jahanian7f90b532012-08-16 22:38:41 +000011931 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11932 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11933 diag::err_abstract_type_in_decl,
11934 AbstractIvarType)) {
11935 // Ivars can not have abstract class types
11936 FD->setInvalidDecl();
11937 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000011938 if (Record && FDTTy->getDecl()->hasObjectMember())
11939 Record->setHasObjectMember(true);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011940 if (Record && FDTTy->getDecl()->hasVolatileMember())
11941 Record->setHasVolatileMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +000011942 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011943 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +000011944 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11945 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11946 QualType T = Context.getObjCObjectPointerType(FD->getType());
11947 FD->setType(T);
Douglas Gregor4581d452013-01-28 19:08:09 +000011948 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11949 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11950 // It's an error in ARC if a field has lifetime.
11951 // We don't want to report this in a system header, though,
11952 // so we just make the field unavailable.
11953 // FIXME: that's really not sufficient; we need to make the type
11954 // itself invalid to, say, initialize or copy.
11955 QualType T = FD->getType();
11956 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11957 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11958 SourceLocation loc = FD->getLocation();
11959 if (getSourceManager().isInSystemHeader(loc)) {
11960 if (!FD->hasAttr<UnavailableAttr>()) {
11961 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11962 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011963 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011964 } else {
11965 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregorbde67cf2013-01-28 20:13:44 +000011966 << T->isBlockPointerType() << Record->getTagKind();
John McCallf85e1932011-06-15 23:02:42 +000011967 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011968 ARCErrReported = true;
John McCallf85e1932011-06-15 23:02:42 +000011969 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011970 } else if (getLangOpts().ObjC1 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011971 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +000011972 Record && !Record->hasObjectMember()) {
Douglas Gregor4581d452013-01-28 19:08:09 +000011973 if (FD->getType()->isObjCObjectPointerType() ||
11974 FD->getType().isObjCGCStrong())
11975 Record->setHasObjectMember(true);
11976 else if (Context.getAsArrayType(FD->getType())) {
11977 QualType BaseType = Context.getBaseElementType(FD->getType());
11978 if (BaseType->isRecordType() &&
11979 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCallf85e1932011-06-15 23:02:42 +000011980 Record->setHasObjectMember(true);
Douglas Gregor4581d452013-01-28 19:08:09 +000011981 else if (BaseType->isObjCObjectPointerType() ||
11982 BaseType.isObjCGCStrong())
11983 Record->setHasObjectMember(true);
John McCallf85e1932011-06-15 23:02:42 +000011984 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +000011985 }
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011986 if (Record && FD->getType().isVolatileQualified())
11987 Record->setHasVolatileMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011988 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +000011989 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +000011990 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +000011991 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000011992
Reid Spencer5f016e22007-07-11 17:01:13 +000011993 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +000011994 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011995 bool Completed = false;
11996 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
11997 if (!CXXRecord->isInvalidDecl()) {
11998 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011999 for (CXXRecordDecl::conversion_iterator
12000 I = CXXRecord->conversion_begin(),
12001 E = CXXRecord->conversion_end(); I != E; ++I)
12002 I.setAccess((*I)->getAccess());
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012003
12004 if (!CXXRecord->isDependentType()) {
Peter Collingbournef51cfb82013-05-20 14:12:25 +000012005 if (CXXRecord->hasUserDeclaredDestructor()) {
12006 // Adjust user-defined destructor exception spec.
12007 if (getLangOpts().CPlusPlus11)
12008 AdjustDestructorExceptionSpec(CXXRecord,
12009 CXXRecord->getDestructor());
12010
12011 // The Microsoft ABI requires that we perform the destructor body
12012 // checks (i.e. operator delete() lookup) at every declaration, as
12013 // any translation unit may need to emit a deleting destructor.
12014 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12015 CheckDestructor(CXXRecord->getDestructor());
12016 }
Sebastian Redl0ee33912011-05-19 05:13:44 +000012017
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012018 // Add any implicitly-declared members to this class.
12019 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12020
12021 // If we have virtual base classes, we may end up finding multiple
12022 // final overriders for a given virtual function. Check for this
12023 // problem now.
12024 if (CXXRecord->getNumVBases()) {
12025 CXXFinalOverriderMap FinalOverriders;
12026 CXXRecord->getFinalOverriders(FinalOverriders);
12027
12028 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12029 MEnd = FinalOverriders.end();
12030 M != MEnd; ++M) {
12031 for (OverridingMethods::iterator SO = M->second.begin(),
12032 SOEnd = M->second.end();
12033 SO != SOEnd; ++SO) {
12034 assert(SO->second.size() > 0 &&
12035 "Virtual function without overridding functions?");
12036 if (SO->second.size() == 1)
12037 continue;
12038
12039 // C++ [class.virtual]p2:
12040 // In a derived class, if a virtual member function of a base
12041 // class subobject has more than one final overrider the
12042 // program is ill-formed.
12043 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divacky31ba6132012-09-06 15:59:27 +000012044 << (const NamedDecl *)M->first << Record;
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012045 Diag(M->first->getLocation(),
12046 diag::note_overridden_virtual_function);
12047 for (OverridingMethods::overriding_iterator
12048 OM = SO->second.begin(),
12049 OMEnd = SO->second.end();
12050 OM != OMEnd; ++OM)
12051 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divacky31ba6132012-09-06 15:59:27 +000012052 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012053
12054 Record->setInvalidDecl();
12055 }
12056 }
12057 CXXRecord->completeDefinition(&FinalOverriders);
12058 Completed = true;
12059 }
12060 }
12061 }
12062 }
12063
12064 if (!Completed)
12065 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +000012066
Richard Smithbe507b62013-02-01 08:12:08 +000012067 if (Record->hasAttrs())
12068 CheckAlignasUnderalignment(Record);
Serge Pavlov122e6012013-06-08 13:29:58 +000012069
Serge Pavlov142ab062013-11-14 02:13:03 +000012070 // Check if the structure/union declaration is a type that can have zero
12071 // size in C. For C this is a language extension, for C++ it may cause
12072 // compatibility problems.
12073 bool CheckForZeroSize;
Serge Pavlov122e6012013-06-08 13:29:58 +000012074 if (!getLangOpts().CPlusPlus) {
Serge Pavlov142ab062013-11-14 02:13:03 +000012075 CheckForZeroSize = true;
12076 } else {
12077 // For C++ filter out types that cannot be referenced in C code.
12078 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12079 CheckForZeroSize =
12080 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12081 !CXXRecord->isDependentType() &&
12082 CXXRecord->isCLike();
12083 }
12084 if (CheckForZeroSize) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012085 bool ZeroSize = true;
Serge Pavlov0dcea352013-06-17 17:18:51 +000012086 bool IsEmpty = true;
12087 unsigned NonBitFields = 0;
Serge Pavlov122e6012013-06-08 13:29:58 +000012088 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlov0dcea352013-06-17 17:18:51 +000012089 E = Record->field_end();
12090 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12091 IsEmpty = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012092 if (I->isUnnamedBitfield()) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012093 if (I->getBitWidthValue(Context) > 0)
12094 ZeroSize = false;
12095 } else {
Serge Pavlov0dcea352013-06-17 17:18:51 +000012096 ++NonBitFields;
12097 QualType FieldType = I->getType();
12098 if (FieldType->isIncompleteType() ||
12099 !Context.getTypeSizeInChars(FieldType).isZero())
12100 ZeroSize = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012101 }
12102 }
12103
Serge Pavlov142ab062013-11-14 02:13:03 +000012104 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12105 // allowed in C++, but warn if its declaration is inside
12106 // extern "C" block.
12107 if (ZeroSize) {
12108 Diag(RecLoc, getLangOpts().CPlusPlus ?
12109 diag::warn_zero_size_struct_union_in_extern_c :
12110 diag::warn_zero_size_struct_union_compat)
12111 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12112 }
Serge Pavlov122e6012013-06-08 13:29:58 +000012113
Serge Pavlov142ab062013-11-14 02:13:03 +000012114 // Structs without named members are extension in C (C99 6.7.2.1p7),
12115 // but are accepted by GCC.
12116 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12117 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12118 diag::ext_no_named_members_in_struct_union)
12119 << Record->isUnion();
Serge Pavlov122e6012013-06-08 13:29:58 +000012120 }
12121 }
Chris Lattnere1e79852008-02-06 00:51:33 +000012122 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +000012123 ObjCIvarDecl **ClsFields =
12124 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +000012125 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +000012126 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012127 // Add ivar's to class's DeclContext.
12128 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12129 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012130 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012131 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +000012132 // Must enforce the rule that ivars in the base classes may not be
12133 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +000012134 if (ID->getSuperClass())
12135 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +000012136 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +000012137 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000012138 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012139 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12140 // Ivar declared in @implementation never belongs to the implementation.
12141 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +000012142 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +000012143 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012144 IMPDecl->setIvarLBraceLoc(LBrac);
12145 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012146 } else if (ObjCCategoryDecl *CDecl =
12147 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012148 // case of ivars in class extension; all other cases have been
12149 // reported as errors elsewhere.
12150 // FIXME. Class extension does not have a LocEnd field.
12151 // CDecl->setLocEnd(RBrac);
12152 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012153 // Diagnose redeclaration of private ivars.
12154 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012155 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012156 if (IDecl) {
12157 if (const ObjCIvarDecl *ClsIvar =
12158 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12159 Diag(ClsFields[i]->getLocation(),
12160 diag::err_duplicate_ivar_declaration);
12161 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12162 continue;
12163 }
Douglas Gregord3297242013-01-16 23:00:23 +000012164 for (ObjCInterfaceDecl::known_extensions_iterator
12165 Ext = IDecl->known_extensions_begin(),
12166 ExtEnd = IDecl->known_extensions_end();
12167 Ext != ExtEnd; ++Ext) {
12168 if (const ObjCIvarDecl *ClsExtIvar
12169 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012170 Diag(ClsFields[i]->getLocation(),
12171 diag::err_duplicate_ivar_declaration);
12172 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12173 continue;
12174 }
12175 }
12176 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012177 ClsFields[i]->setLexicalDeclContext(CDecl);
12178 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012179 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012180 CDecl->setIvarLBraceLoc(LBrac);
12181 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +000012182 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +000012183 }
Daniel Dunbar7d076642008-10-03 17:33:35 +000012184
12185 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000012186 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +000012187}
12188
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012189/// \brief Determine whether the given integral value is representable within
12190/// the given type T.
12191static bool isRepresentableIntegerValue(ASTContext &Context,
12192 llvm::APSInt &Value,
12193 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012194 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +000012195 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012196
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012197 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +000012198 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012199 --BitWidth;
12200 return Value.getActiveBits() <= BitWidth;
12201 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012202 return Value.getMinSignedBits() <= BitWidth;
12203}
12204
12205// \brief Given an integral type, return the next larger integral type
12206// (or a NULL type of no such type exists).
12207static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12208 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12209 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012210 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012211 const unsigned NumTypes = 4;
12212 QualType SignedIntegralTypes[NumTypes] = {
12213 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12214 };
12215 QualType UnsignedIntegralTypes[NumTypes] = {
12216 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12217 Context.UnsignedLongLongTy
12218 };
12219
12220 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +000012221 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12222 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012223 for (unsigned I = 0; I != NumTypes; ++I)
12224 if (Context.getTypeSize(Types[I]) > BitWidth)
12225 return Types[I];
12226
12227 return QualType();
12228}
12229
Douglas Gregor879fd492009-03-17 19:05:46 +000012230EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12231 EnumConstantDecl *LastEnumConst,
12232 SourceLocation IdLoc,
12233 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +000012234 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012235 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012236 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +000012237 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +000012238
12239 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12240 Val = 0;
12241
Eli Friedman19efa3e2011-12-06 00:10:34 +000012242 if (Val)
12243 Val = DefaultLvalueConversion(Val).take();
12244
Douglas Gregor4912c342009-11-06 00:03:12 +000012245 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012246 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +000012247 EltTy = Context.DependentTy;
12248 else {
Douglas Gregor4912c342009-11-06 00:03:12 +000012249 SourceLocation ExpLoc;
Richard Smith80ad52f2013-01-02 11:42:31 +000012250 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012251 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012252 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12253 // constant-expression in the enumerator-definition shall be a converted
12254 // constant expression of the underlying type.
12255 EltTy = Enum->getIntegerType();
12256 ExprResult Converted =
12257 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12258 CCEK_Enumerator);
12259 if (Converted.isInvalid())
12260 Val = 0;
12261 else
12262 Val = Converted.take();
12263 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +000012264 !(Val = VerifyIntegerConstantExpression(Val,
12265 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012266 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +000012267 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012268 if (Enum->isFixed()) {
12269 EltTy = Enum->getIntegerType();
12270
Richard Smith8ef7b202012-01-18 23:55:52 +000012271 // In Obj-C and Microsoft mode, require the enumeration value to be
12272 // representable in the underlying type of the enumeration. In C++11,
12273 // we perform a non-narrowing conversion as part of converted constant
12274 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +000012275 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012276 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +000012277 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +000012278 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +000012279 } else
12280 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +000012281 } else
John Wiegley429bb272011-04-08 18:41:53 +000012282 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +000012283 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012284 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012285 // If the underlying type is not fixed, the type of each enumerator
12286 // is the type of its initializing value:
12287 // - If an initializer is specified for an enumerator, the
12288 // initializing value has the same type as the expression.
12289 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +000012290 } else {
12291 // C99 6.7.2.2p2:
12292 // The expression that defines the value of an enumeration constant
12293 // shall be an integer constant expression that has a value
12294 // representable as an int.
12295
12296 // Complain if the value is not representable in an int.
12297 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12298 Diag(IdLoc, diag::ext_enum_value_not_int)
12299 << EnumVal.toString(10) << Val->getSourceRange()
12300 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12301 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12302 // Force the type of the expression to 'int'.
12303 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12304 }
12305 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012306 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012307 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012308 }
12309 }
Mike Stump1eb44332009-09-09 15:08:12 +000012310
Douglas Gregor879fd492009-03-17 19:05:46 +000012311 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012312 if (Enum->isDependentType())
12313 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012314 else if (!LastEnumConst) {
12315 // C++0x [dcl.enum]p5:
12316 // If the underlying type is not fixed, the type of each enumerator
12317 // is the type of its initializing value:
12318 // - If no initializer is specified for the first enumerator, the
12319 // initializing value has an unspecified integral type.
12320 //
12321 // GCC uses 'int' for its unspecified integral type, as does
12322 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012323 if (Enum->isFixed()) {
12324 EltTy = Enum->getIntegerType();
12325 }
12326 else {
12327 EltTy = Context.IntTy;
12328 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012329 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000012330 // Assign the last value + 1.
12331 EnumVal = LastEnumConst->getInitVal();
12332 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012333 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000012334
12335 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012336 if (EnumVal < LastEnumConst->getInitVal()) {
12337 // C++0x [dcl.enum]p5:
12338 // If the underlying type is not fixed, the type of each enumerator
12339 // is the type of its initializing value:
12340 //
12341 // - Otherwise the type of the initializing value is the same as
12342 // the type of the initializing value of the preceding enumerator
12343 // unless the incremented value is not representable in that type,
12344 // in which case the type is an unspecified integral type
12345 // sufficient to contain the incremented value. If no such type
12346 // exists, the program is ill-formed.
12347 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012348 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012349 // There is no integral type larger enough to represent this
12350 // value. Complain, then allow the value to wrap around.
12351 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000012352 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012353 ++EnumVal;
12354 if (Enum->isFixed())
12355 // When the underlying type is fixed, this is ill-formed.
12356 Diag(IdLoc, diag::err_enumerator_wrapped)
12357 << EnumVal.toString(10)
12358 << EltTy;
12359 else
12360 Diag(IdLoc, diag::warn_enumerator_too_large)
12361 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012362 } else {
12363 EltTy = T;
12364 }
12365
12366 // Retrieve the last enumerator's value, extent that type to the
12367 // type that is supposed to be large enough to represent the incremented
12368 // value, then increment.
12369 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000012370 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000012371 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012372 ++EnumVal;
12373
12374 // If we're not in C++, diagnose the overflow of enumerator values,
12375 // which in C99 means that the enumerator value is not representable in
12376 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12377 // permits enumerator values that are representable in some larger
12378 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000012379 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012380 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000012381 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012382 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12383 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12384 Diag(IdLoc, diag::ext_enum_value_not_int)
12385 << EnumVal.toString(10) << 1;
12386 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012387 }
12388 }
Mike Stump1eb44332009-09-09 15:08:12 +000012389
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012390 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012391 // Make the enumerator value match the signedness and size of the
12392 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000012393 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000012394 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012395 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012396
Douglas Gregor879fd492009-03-17 19:05:46 +000012397 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000012398 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000012399}
12400
12401
John McCall5b629aa2010-10-22 23:36:17 +000012402Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12403 SourceLocation IdLoc, IdentifierInfo *Id,
12404 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000012405 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000012406 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000012407 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000012408 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000012409
Chris Lattner31e05722007-08-26 06:24:45 +000012410 // The scope passed in may not be a decl scope. Zip up the scope tree until
12411 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000012412 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000012413
Reid Spencer5f016e22007-07-11 17:01:13 +000012414 // Verify that there isn't already something declared with this name in this
12415 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000012416 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000012417 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000012418 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000012419 // Maybe we will complain about the shadowed template parameter.
12420 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12421 // Just pretend that we didn't see the previous declaration.
12422 PrevDecl = 0;
12423 }
12424
12425 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012426 // When in C++, we may get a TagDecl with the same name; in this case the
12427 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000012428 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012429 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000012430 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012431 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000012432 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000012433 else
Chris Lattner3c73c412008-11-19 08:23:25 +000012434 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000012435 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000012436 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000012437 }
12438 }
12439
Aaron Ballmanf8167872012-07-19 03:12:23 +000012440 // C++ [class.mem]p15:
12441 // If T is the name of a class, then each of the following shall have a name
12442 // different from T:
12443 // - every enumerator of every member of class T that is an unscoped
12444 // enumerated type
Douglas Gregora6e937c2010-10-15 13:21:21 +000012445 if (CXXRecordDecl *Record
12446 = dyn_cast<CXXRecordDecl>(
12447 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballmanf8167872012-07-19 03:12:23 +000012448 if (!TheEnumDecl->isScoped() &&
12449 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregora6e937c2010-10-15 13:21:21 +000012450 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12451
John McCall5b629aa2010-10-22 23:36:17 +000012452 EnumConstantDecl *New =
12453 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000012454
John McCall92f88312010-01-23 00:46:32 +000012455 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000012456 // Process attributes.
12457 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12458
12459 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000012460 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000012461 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000012462 }
Douglas Gregor45579f52008-12-17 02:04:30 +000012463
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000012464 ActOnDocumentableDecl(New);
12465
John McCalld226f652010-08-21 09:40:31 +000012466 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000012467}
12468
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012469// Returns true when the enum initial expression does not trigger the
12470// duplicate enum warning. A few common cases are exempted as follows:
12471// Element2 = Element1
12472// Element2 = Element1 + 1
12473// Element2 = Element1 - 1
12474// Where Element2 and Element1 are from the same enum.
12475static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12476 Expr *InitExpr = ECD->getInitExpr();
12477 if (!InitExpr)
12478 return true;
12479 InitExpr = InitExpr->IgnoreImpCasts();
12480
12481 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12482 if (!BO->isAdditiveOp())
12483 return true;
12484 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12485 if (!IL)
12486 return true;
12487 if (IL->getValue() != 1)
12488 return true;
12489
12490 InitExpr = BO->getLHS();
12491 }
12492
12493 // This checks if the elements are from the same enum.
12494 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12495 if (!DRE)
12496 return true;
12497
12498 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12499 if (!EnumConstant)
12500 return true;
12501
12502 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12503 Enum)
12504 return true;
12505
12506 return false;
12507}
12508
12509struct DupKey {
12510 int64_t val;
12511 bool isTombstoneOrEmptyKey;
12512 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12513 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12514};
12515
12516static DupKey GetDupKey(const llvm::APSInt& Val) {
12517 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12518 false);
12519}
12520
12521struct DenseMapInfoDupKey {
12522 static DupKey getEmptyKey() { return DupKey(0, true); }
12523 static DupKey getTombstoneKey() { return DupKey(1, true); }
12524 static unsigned getHashValue(const DupKey Key) {
12525 return (unsigned)(Key.val * 37);
12526 }
12527 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12528 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12529 LHS.val == RHS.val;
12530 }
12531};
12532
12533// Emits a warning when an element is implicitly set a value that
12534// a previous element has already been set to.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012535static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12536 EnumDecl *Enum,
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012537 QualType EnumType) {
12538 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12539 Enum->getLocation()) ==
12540 DiagnosticsEngine::Ignored)
12541 return;
12542 // Avoid anonymous enums
12543 if (!Enum->getIdentifier())
12544 return;
12545
12546 // Only check for small enums.
12547 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12548 return;
12549
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012550 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12551 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012552
12553 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12554 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12555 ValueToVectorMap;
12556
12557 DuplicatesVector DupVector;
12558 ValueToVectorMap EnumMap;
12559
12560 // Populate the EnumMap with all values represented by enum constants without
12561 // an initialier.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012562 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramerefac8da2013-04-07 14:10:40 +000012563 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012564
12565 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12566 // this constant. Skip this enum since it may be ill-formed.
12567 if (!ECD) {
12568 return;
12569 }
12570
12571 if (ECD->getInitExpr())
12572 continue;
12573
12574 DupKey Key = GetDupKey(ECD->getInitVal());
12575 DeclOrVector &Entry = EnumMap[Key];
12576
12577 // First time encountering this value.
12578 if (Entry.isNull())
12579 Entry = ECD;
12580 }
12581
12582 // Create vectors for any values that has duplicates.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012583 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012584 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12585 if (!ValidDuplicateEnum(ECD, Enum))
12586 continue;
12587
12588 DupKey Key = GetDupKey(ECD->getInitVal());
12589
12590 DeclOrVector& Entry = EnumMap[Key];
12591 if (Entry.isNull())
12592 continue;
12593
12594 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12595 // Ensure constants are different.
12596 if (D == ECD)
12597 continue;
12598
12599 // Create new vector and push values onto it.
12600 ECDVector *Vec = new ECDVector();
12601 Vec->push_back(D);
12602 Vec->push_back(ECD);
12603
12604 // Update entry to point to the duplicates vector.
12605 Entry = Vec;
12606
12607 // Store the vector somewhere we can consult later for quick emission of
12608 // diagnostics.
12609 DupVector.push_back(Vec);
12610 continue;
12611 }
12612
12613 ECDVector *Vec = Entry.get<ECDVector*>();
12614 // Make sure constants are not added more than once.
12615 if (*Vec->begin() == ECD)
12616 continue;
12617
12618 Vec->push_back(ECD);
12619 }
12620
12621 // Emit diagnostics.
12622 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12623 DupVectorEnd = DupVector.end();
12624 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12625 ECDVector *Vec = *DupVectorIter;
12626 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12627
12628 // Emit warning for one enum constant.
12629 ECDVector::iterator I = Vec->begin();
12630 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12631 << (*I)->getName() << (*I)->getInitVal().toString(10)
12632 << (*I)->getSourceRange();
12633 ++I;
12634
12635 // Emit one note for each of the remaining enum constants with
12636 // the same value.
12637 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12638 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12639 << (*I)->getName() << (*I)->getInitVal().toString(10)
12640 << (*I)->getSourceRange();
12641 delete Vec;
12642 }
12643}
12644
Mike Stumpc6e35aa2009-05-16 07:06:02 +000012645void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000012646 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012647 ArrayRef<Decl *> Elements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012648 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000012649 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000012650 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012651
12652 if (Attr)
12653 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000012654
Eli Friedmaned0716b2009-12-11 01:34:50 +000012655 if (Enum->isDependentType()) {
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012656 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012657 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012658 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012659 if (!ECD) continue;
12660
12661 ECD->setType(EnumType);
12662 }
12663
John McCall1b5a6182010-05-06 08:49:23 +000012664 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012665 return;
12666 }
12667
Chris Lattnere37f0be2007-08-28 05:10:31 +000012668 // TODO: If the result value doesn't fit in an int, it must be a long or long
12669 // long value. ISO C does not support this, but GCC does as an extension,
12670 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012671 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12672 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12673 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012674
Chris Lattnerac609682007-08-28 06:15:15 +000012675 // Verify that all the values are okay, compute the size of the values, and
12676 // reverse the list.
12677 unsigned NumNegativeBits = 0;
12678 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000012679
Chris Lattnerac609682007-08-28 06:15:15 +000012680 // Keep track of whether all elements have type int.
12681 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000012682
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012683 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012684 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012685 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000012686 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000012687
Chris Lattner211a30e2007-08-28 05:27:00 +000012688 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000012689
Chris Lattnerac609682007-08-28 06:15:15 +000012690 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000012691 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000012692 NumPositiveBits = std::max(NumPositiveBits,
12693 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000012694 else
Chris Lattner21dd8212008-01-14 21:47:29 +000012695 NumNegativeBits = std::max(NumNegativeBits,
12696 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000012697
Chris Lattnerac609682007-08-28 06:15:15 +000012698 // Keep track of whether every enum element has type int (very commmon).
12699 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000012700 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000012701 }
Mike Stump1eb44332009-09-09 15:08:12 +000012702
Chris Lattnerac609682007-08-28 06:15:15 +000012703 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000012704 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012705 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012706
John McCall842aef82009-12-09 09:09:27 +000012707 // C++0x N3000 [conv.prom]p3:
12708 // An rvalue of an unscoped enumeration type whose underlying
12709 // type is not fixed can be converted to an rvalue of the first
12710 // of the following types that can represent all the values of
12711 // the enumeration: int, unsigned int, long int, unsigned long
12712 // int, long long int, or unsigned long long int.
12713 // C99 6.4.4.3p2:
12714 // An identifier declared as an enumeration constant has type int.
12715 // The C99 rule is modified by a gcc extension
12716 QualType BestPromotionType;
12717
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012718 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000012719 // -fshort-enums is the equivalent to specifying the packed attribute on all
12720 // enum definitions.
12721 if (LangOpts.ShortEnums)
12722 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012723
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012724 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000012725 BestType = Enum->getIntegerType();
12726 if (BestType->isPromotableIntegerType())
12727 BestPromotionType = Context.getPromotedIntegerType(BestType);
12728 else
12729 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000012730 // We don't need to set BestWidth, because BestType is going to be the type
12731 // of the enumerators, but we do anyway because otherwise some compilers
12732 // warn that it might be used uninitialized.
12733 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012734 }
12735 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000012736 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000012737 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012738 // If it's packed, check also if it fits a char or a short.
12739 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012740 BestType = Context.SignedCharTy;
12741 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000012742 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012743 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012744 BestType = Context.ShortTy;
12745 BestWidth = ShortWidth;
12746 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012747 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012748 BestWidth = IntWidth;
12749 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012750 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012751
John McCall842aef82009-12-09 09:09:27 +000012752 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012753 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000012754 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012755 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012756
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012757 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000012758 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12759 BestType = Context.LongLongTy;
12760 }
12761 }
John McCall842aef82009-12-09 09:09:27 +000012762 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000012763 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012764 // If there is no negative value, figure out the smallest type that fits
12765 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012766 // If it's packed, check also if it fits a char or a short.
12767 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012768 BestType = Context.UnsignedCharTy;
12769 BestPromotionType = Context.IntTy;
12770 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012771 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012772 BestType = Context.UnsignedShortTy;
12773 BestPromotionType = Context.IntTy;
12774 BestWidth = ShortWidth;
12775 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012776 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012777 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012778 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012779 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012780 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012781 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012782 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000012783 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012784 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012785 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012786 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000012787 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012788 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012789 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000012790 "How could an initializer get larger than ULL?");
12791 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012792 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012793 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012794 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000012795 }
12796 }
Mike Stump1eb44332009-09-09 15:08:12 +000012797
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012798 // Loop over all of the enumerator constants, changing their types to match
12799 // the type of the enum if needed.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012800 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +000012801 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012802 if (!ECD) continue; // Already issued a diagnostic.
12803
12804 // Standard C says the enumerators have int type, but we allow, as an
12805 // extension, the enumerators to be larger than int size. If each
12806 // enumerator value fits in an int, type it as an int, otherwise type it the
12807 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12808 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012809
12810 // Determine whether the value fits into an int.
12811 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012812
12813 // If it fits into an integer type, force it. Otherwise force it to match
12814 // the enum decl type.
12815 QualType NewTy;
12816 unsigned NewWidth;
12817 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000012818 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000012819 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012820 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012821 NewTy = Context.IntTy;
12822 NewWidth = IntWidth;
12823 NewSign = true;
12824 } else if (ECD->getType() == BestType) {
12825 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000012826 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012827 // C++ [dcl.enum]p4: Following the closing brace of an
12828 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012829 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012830 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012831 continue;
12832 } else {
12833 NewTy = BestType;
12834 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000012835 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012836 }
12837
12838 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000012839 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012840 InitVal.setIsSigned(NewSign);
12841 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000012842
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012843 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000012844 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000012845 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000012846 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000012847 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000012848 ECD->getInitExpr(),
12849 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000012850 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000012851 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012852 // C++ [dcl.enum]p4: Following the closing brace of an
12853 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012854 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012855 ECD->setType(EnumType);
12856 else
12857 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012858 }
Mike Stump1eb44332009-09-09 15:08:12 +000012859
John McCall1b5a6182010-05-06 08:49:23 +000012860 Enum->completeDefinition(BestType, BestPromotionType,
12861 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000012862
12863 // If we're declaring a function, ensure this decl isn't forgotten about -
12864 // it needs to go into the function scope.
12865 if (InFunctionDeclarator)
12866 DeclsInPrototypeScope.push_back(Enum);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012867
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012868 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smithbe507b62013-02-01 08:12:08 +000012869
12870 // Now that the enum type is defined, ensure it's not been underaligned.
12871 if (Enum->hasAttrs())
12872 CheckAlignasUnderalignment(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +000012873}
12874
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012875Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12876 SourceLocation StartLoc,
12877 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000012878 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000012879
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000012880 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012881 AsmString, StartLoc,
12882 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012883 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000012884 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000012885}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012886
Douglas Gregor5948ae12012-01-03 18:04:46 +000012887DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12888 SourceLocation ImportLoc,
12889 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000012890 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000012891 Module::AllVisible,
12892 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000012893 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012894 return true;
12895
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012896 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregor15de72c2011-12-02 23:23:56 +000012897 Module *ModCheck = Mod;
12898 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12899 // If we've run out of module parents, just drop the remaining identifiers.
12900 // We need the length to be consistent.
12901 if (!ModCheck)
12902 break;
12903 ModCheck = ModCheck->Parent;
12904
12905 IdentifierLocs.push_back(Path[I].second);
12906 }
12907
12908 ImportDecl *Import = ImportDecl::Create(Context,
12909 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000012910 AtLoc.isValid()? AtLoc : ImportLoc,
12911 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000012912 Context.getTranslationUnitDecl()->addDecl(Import);
12913 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012914}
12915
Richard Smith26297f52013-11-15 04:24:58 +000012916void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
12917 // FIXME: Should we synthesize an ImportDecl here?
12918 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
12919 /*Complain=*/true);
12920}
12921
Douglas Gregorca2ab452013-01-12 01:29:50 +000012922void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12923 // Create the implicit import declaration.
12924 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12925 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12926 Loc, Mod, Loc);
12927 TU->addDecl(ImportD);
12928 Consumer.HandleImplicitImportDecl(ImportD);
12929
12930 // Make the module visible.
Douglas Gregor906d66a2013-03-20 21:10:35 +000012931 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12932 /*Complain=*/false);
Douglas Gregorca2ab452013-01-12 01:29:50 +000012933}
12934
David Chisnall5f3c1632012-02-18 16:12:34 +000012935void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12936 IdentifierInfo* AliasName,
12937 SourceLocation PragmaLoc,
12938 SourceLocation NameLoc,
12939 SourceLocation AliasNameLoc) {
12940 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12941 LookupOrdinaryName);
12942 AsmLabelAttr *Attr =
12943 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000012944
12945 if (PrevDecl)
12946 PrevDecl->addAttr(Attr);
12947 else
12948 (void)ExtnameUndeclaredIdentifiers.insert(
12949 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12950}
12951
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012952void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12953 SourceLocation PragmaLoc,
12954 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012955 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012956
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012957 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000012958 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000012959 } else {
12960 (void)WeakUndeclaredIdentifiers.insert(
12961 std::pair<IdentifierInfo*,WeakInfo>
12962 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012963 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012964}
12965
12966void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12967 IdentifierInfo* AliasName,
12968 SourceLocation PragmaLoc,
12969 SourceLocation NameLoc,
12970 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012971 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12972 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000012973 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012974
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012975 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000012976 if (!PrevDecl->hasAttr<AliasAttr>())
12977 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000012978 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000012979 } else {
12980 (void)WeakUndeclaredIdentifiers.insert(
12981 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012982 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012983}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000012984
12985Decl *Sema::getObjCDeclContext() const {
12986 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12987}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012988
12989AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000012990 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012991 return D->getAvailability();
12992}