blob: 9281951a814b2518bc50851adf31b1cd3e173f0f [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 Smith37e849a2013-08-14 20:16:31 +00006740 if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() &&
6741 NewFD->getResultType()->isUndeducedType()) {
6742 // If the function template is referenced directly (for instance, as a
6743 // member of the current instantiation), pretend it has a dependent type.
6744 // This is not really justified by the standard, but is the only sane
6745 // thing to do.
6746 const FunctionProtoType *FPT =
6747 NewFD->getType()->castAs<FunctionProtoType>();
6748 QualType Result = SubstAutoType(FPT->getResultType(),
6749 Context.DependentTy);
6750 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6751 FPT->getExtProtoInfo()));
6752 }
6753
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006754 // C++ [dcl.fct.spec]p3:
David Blaikied662a792011-10-19 22:56:21 +00006755 // The inline specifier shall not appear on a block scope function
6756 // declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006757 if (isInline && !NewFD->isInvalidDecl()) {
6758 if (CurContext->isFunctionOrMethod()) {
6759 // 'inline' is not allowed on block scope function declaration.
6760 Diag(D.getDeclSpec().getInlineSpecLoc(),
6761 diag::err_inline_declaration_block_scope) << Name
6762 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6763 }
6764 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006765
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006766 // C++ [dcl.fct.spec]p6:
6767 // The explicit specifier shall be used only in the declaration of a
David Blaikied662a792011-10-19 22:56:21 +00006768 // constructor or conversion function within its class definition;
6769 // see 12.3.1 and 12.3.2.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006770 if (isExplicit && !NewFD->isInvalidDecl()) {
6771 if (!CurContext->isRecord()) {
6772 // 'explicit' was specified outside of the class.
6773 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6774 diag::err_explicit_out_of_class)
6775 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6776 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6777 !isa<CXXConversionDecl>(NewFD)) {
6778 // 'explicit' was specified on a function that wasn't a constructor
6779 // or conversion function.
6780 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6781 diag::err_explicit_non_ctor_or_conv_function)
6782 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6783 }
6784 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00006785
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006786 if (isConstexpr) {
Richard Smith21c8fa82013-01-14 05:37:29 +00006787 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006788 // are implicitly inline.
6789 NewFD->setImplicitlyInline();
6790
Richard Smith21c8fa82013-01-14 05:37:29 +00006791 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006792 // be either constructors or to return a literal type. Therefore,
6793 // destructors cannot be declared constexpr.
6794 if (isa<CXXDestructorDecl>(NewFD))
Richard Smith9f569cc2011-10-01 02:31:28 +00006795 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006796 }
6797
Douglas Gregor8d267c52011-09-09 02:06:17 +00006798 // If __module_private__ was specified, mark the function accordingly.
6799 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregord023aec2011-09-09 20:53:38 +00006800 if (isFunctionTemplateSpecialization) {
6801 SourceLocation ModulePrivateLoc
6802 = D.getDeclSpec().getModulePrivateSpecLoc();
6803 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6804 << 0
6805 << FixItHint::CreateRemoval(ModulePrivateLoc);
6806 } else {
6807 NewFD->setModulePrivate();
6808 if (FunctionTemplate)
6809 FunctionTemplate->setModulePrivate();
6810 }
Douglas Gregor8d267c52011-09-09 02:06:17 +00006811 }
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006812
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006813 if (isFriend) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006814 if (FunctionTemplate) {
Richard Smith22050f22013-07-17 23:53:16 +00006815 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006816 FunctionTemplate->setAccess(AS_public);
6817 }
Richard Smith22050f22013-07-17 23:53:16 +00006818 NewFD->setObjectOfFriendDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006819 NewFD->setAccess(AS_public);
6820 }
6821
Douglas Gregor45fa5602011-11-07 20:56:01 +00006822 // If a function is defined as defaulted or deleted, mark it as such now.
6823 switch (D.getFunctionDefinitionKind()) {
6824 case FDK_Declaration:
6825 case FDK_Definition:
6826 break;
6827
6828 case FDK_Defaulted:
6829 NewFD->setDefaulted();
6830 break;
6831
6832 case FDK_Deleted:
6833 NewFD->setDeletedAsWritten();
6834 break;
6835 }
6836
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00006837 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6838 D.isFunctionDefinition()) {
Douglas Gregor45fa5602011-11-07 20:56:01 +00006839 // C++ [class.mfct]p2:
6840 // A member function may be defined (8.4) in its class definition, in
6841 // which case it is an inline member function (7.1.2)
John McCallbfdcdc82010-12-15 04:00:32 +00006842 NewFD->setImplicitlyInline();
6843 }
6844
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006845 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6846 !CurContext->isRecord()) {
6847 // C++ [class.static]p1:
6848 // A data or function member of a class may be declared static
6849 // in a class definition, in which case it is a static member of
6850 // the class.
6851
6852 // Complain about the 'static' specifier if it's on an out-of-line
6853 // member function definition.
6854 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6855 diag::err_static_out_of_line)
6856 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6857 }
Richard Smith444d3842012-10-20 08:26:51 +00006858
6859 // C++11 [except.spec]p15:
6860 // A deallocation function with no exception-specification is treated
6861 // as if it were specified with noexcept(true).
6862 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6863 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6864 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006865 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith444d3842012-10-20 08:26:51 +00006866 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6867 EPI.ExceptionSpecType = EST_BasicNoexcept;
6868 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00006869 FPT->getArgTypes(), EPI));
Richard Smith444d3842012-10-20 08:26:51 +00006870 }
David Majnemerd2b0cf32013-10-20 05:40:29 +00006871
6872 // C++11 [replacement.functions]p3:
6873 // The program's definitions shall not be specified as inline.
David Majnemer3abf5f62013-10-21 00:25:32 +00006874 //
6875 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
David Majnemerd2b0cf32013-10-20 05:40:29 +00006876 if (isInline && NewFD->isReplaceableGlobalAllocationFunction())
6877 Diag(D.getDeclSpec().getInlineSpecLoc(),
6878 diag::err_operator_new_delete_declared_inline)
6879 << NewFD->getDeclName();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00006880 }
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006881
6882 // Filter out previous declarations that don't match the scope.
Richard Smitha41c97a2013-09-20 01:15:31 +00006883 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraind7e19ce2011-10-11 00:28:49 +00006884 isExplicitSpecialization ||
6885 isFunctionTemplateSpecialization);
Richard Smithdd9459f2013-08-13 18:18:50 +00006886
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006887 // Handle GNU asm-label extension (encoded as an attribute).
6888 if (Expr *E = (Expr*) D.getAsmLabel()) {
6889 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00006890 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00006891 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6892 SE->getString()));
David Chisnall5f3c1632012-02-18 16:12:34 +00006893 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6894 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6895 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6896 if (I != ExtnameUndeclaredIdentifiers.end()) {
6897 NewFD->addAttr(I->second);
6898 ExtnameUndeclaredIdentifiers.erase(I);
6899 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006900 }
6901
Chris Lattner2dbd2852009-04-25 06:12:16 +00006902 // Copy the parameter declarations from the declarator D to the function
6903 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006904 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00006905 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006906 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006907
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006908 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6909 // function that takes no arguments, not a function that takes a
6910 // single void argument.
6911 // We let through "const void" here because Sema::GetTypeForDeclarator
6912 // already checks for that case.
6913 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6914 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006915 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00006916 // Empty arg list, don't push any params.
Eli Friedman7c3c6bc2012-09-20 01:40:23 +00006917 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006918 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006919 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00006920 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006921 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6922 Param->setDeclContext(NewFD);
6923 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00006924
6925 if (Param->isInvalidDecl())
6926 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00006927 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006928 }
Mike Stump1eb44332009-09-09 15:08:12 +00006929
John McCall183700f2009-09-21 23:43:11 +00006930 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00006931 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006932 // following example, we'll need to synthesize (unnamed)
6933 // parameters for use in the declaration.
6934 //
6935 // @code
6936 // typedef void fn(int);
6937 // fn f;
6938 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00006939
Chris Lattner1ad9b282009-04-25 06:03:53 +00006940 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00006941 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6942 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00006943 ParmVarDecl *Param =
6944 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCallfb44de92011-05-01 22:35:37 +00006945 Param->setScopeInfo(0, Params.size());
Chris Lattner1ad9b282009-04-25 06:03:53 +00006946 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006947 }
Chris Lattner84bb9442009-04-25 18:38:18 +00006948 } else {
6949 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6950 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00006951 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00006952
Chris Lattner2dbd2852009-04-25 06:12:16 +00006953 // Finally, we know we have the right number of parameters, install them.
David Blaikie4278c652011-09-21 18:16:56 +00006954 NewFD->setParams(Params);
Mike Stump1eb44332009-09-09 15:08:12 +00006955
James Molloy16f1f712012-02-29 10:24:19 +00006956 // Find all anonymous symbols defined during the declaration of this function
6957 // and add to NewFD. This lets us track decls such 'enum Y' in:
6958 //
6959 // void f(enum Y {AA} x) {}
6960 //
6961 // which would otherwise incorrectly end up in the translation unit scope.
6962 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6963 DeclsInPrototypeScope.clear();
6964
Richard Smith7586a6e2013-01-30 05:45:05 +00006965 if (D.getDeclSpec().isNoreturnSpecified())
6966 NewFD->addAttr(
6967 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6968 Context));
6969
Richard Smithb03a9df2012-03-13 05:56:40 +00006970 // Functions returning a variably modified type violate C99 6.7.5.2p2
6971 // because all functions have linkage.
6972 if (!NewFD->isInvalidDecl() &&
6973 NewFD->getResultType()->isVariablyModifiedType()) {
6974 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6975 NewFD->setInvalidDecl();
6976 }
6977
Rafael Espindola98ae8342012-05-10 02:50:16 +00006978 // Handle attributes.
Richard Smith4a97b8e2013-08-29 00:47:48 +00006979 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindola98ae8342012-05-10 02:50:16 +00006980
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006981 QualType RetType = NewFD->getResultType();
6982 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6983 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6984 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6985 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006986 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramera32966f2013-10-16 16:21:04 +00006987 // Attach the attribute to the new decl. Don't apply the attribute if it
6988 // returns an instance of the class (e.g. assignment operators).
6989 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain97c81bf2012-11-13 21:23:31 +00006990 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6991 Context));
6992 }
Kaelyn Uhrain51ceb7b2012-11-12 23:48:05 +00006993 }
6994
David Blaikie4e4d0842012-03-11 07:00:24 +00006995 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00006996 // Perform semantic checking on the function declaration.
Douglas Gregor89b9f102011-06-06 15:22:55 +00006997 bool isExplicitSpecialization=false;
David Majnemerc371db62013-07-06 02:13:46 +00006998 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6999 CheckMain(NewFD, D.getDeclSpec());
7000
David Majnemere9f6f332013-09-16 22:44:20 +00007001 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7002 CheckMSVCRTEntryPoint(NewFD);
7003
David Majnemerc371db62013-07-06 02:13:46 +00007004 if (!NewFD->isInvalidDecl())
Richard Smithb03a9df2012-03-13 05:56:40 +00007005 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7006 isExplicitSpecialization));
Fariborz Jahanian37c765a2012-09-05 17:52:12 +00007007 else if (!Previous.empty())
Richard Smithdd9459f2013-08-13 18:18:50 +00007008 // Make graceful recovery from an invalid redeclaration.
7009 D.setRedeclaration(true);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007010 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007011 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7012 "previous declaration set still overloaded");
7013 } else {
7014 // If the declarator is a template-id, translate the parser's template
7015 // argument list into our AST format.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007016 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7017 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7018 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7019 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramer5354e772012-08-23 23:38:35 +00007020 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007021 TemplateId->NumArgs);
7022 translateTemplateArguments(TemplateArgsPtr,
7023 TemplateArgs);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007024
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007025 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00007026
Douglas Gregor89b9f102011-06-06 15:22:55 +00007027 if (NewFD->isInvalidDecl()) {
7028 HasExplicitTemplateArgs = false;
7029 } else if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00007030 // Function template with explicit template arguments.
7031 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7032 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7033
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007034 HasExplicitTemplateArgs = false;
7035 } else if (!isFunctionTemplateSpecialization &&
7036 !D.getDeclSpec().isFriendSpecified()) {
7037 // We have encountered something that the user meant to be a
7038 // specialization (because it has explicitly-specified template
7039 // arguments) but that was not introduced with a "template<>" (or had
7040 // too few of them).
Larisse Voufoef4579c2013-08-06 01:03:05 +00007041 // FIXME: Differentiate between attempts for explicit instantiations
7042 // (starting with "template") and the rest.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007043 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7044 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7045 << FixItHint::CreateInsertion(
Daniel Dunbar96a00142012-03-09 18:35:03 +00007046 D.getDeclSpec().getLocStart(),
David Blaikied662a792011-10-19 22:56:21 +00007047 "template<> ");
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007048 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00007049 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007050 // "friend void foo<>(int);" is an implicit specialization decl.
7051 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00007052 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007053 } else if (isFriend && isFunctionTemplateSpecialization) {
7054 // This combination is only possible in a recovery case; the user
7055 // wrote something like:
7056 // template <> friend void foo(int);
7057 // which we're recovering from as if the user had written:
7058 // friend void foo<>(int);
7059 // Go ahead and fake up a template id.
7060 HasExplicitTemplateArgs = true;
7061 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7062 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007063 }
John McCall29ae6e52010-10-13 05:45:15 +00007064
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007065 // If it's a friend (and only if it's a friend), it's possible
7066 // that either the specialized function type or the specialized
7067 // template is dependent, and therefore matching will fail. In
7068 // this case, don't check the specialization yet.
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007069 bool InstantiationDependent = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007070 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregor33ab0da2011-10-09 20:59:17 +00007071 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7072 TemplateSpecializationType::anyDependentTemplateArguments(
7073 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7074 InstantiationDependent))) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007075 assert(HasExplicitTemplateArgs &&
7076 "friend function specialization without template args");
7077 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7078 Previous))
7079 NewFD->setInvalidDecl();
7080 } else if (isFunctionTemplateSpecialization) {
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007081 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetab01add2011-06-03 13:59:45 +00007082 && !isFriend) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007083 isDependentClassScopeExplicitSpecialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00007084 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007085 diag::ext_function_specialization_in_class :
7086 diag::err_function_specialization_in_class)
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007087 << NewFD->getDeclName();
Douglas Gregoreef7ac52011-03-16 19:27:09 +00007088 } else if (CheckFunctionTemplateSpecialization(NewFD,
7089 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7090 Previous))
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007091 NewFD->setInvalidDecl();
Douglas Gregore885e182011-05-21 18:53:30 +00007092
7093 // C++ [dcl.stc]p1:
7094 // A storage-class-specifier shall not be specified in an explicit
7095 // specialization (14.7.3)
Richard Trieu62ab0102013-05-16 02:14:08 +00007096 FunctionTemplateSpecializationInfo *Info =
7097 NewFD->getTemplateSpecializationInfo();
7098 if (Info && SC != SC_None) {
7099 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor0f9dc862011-06-17 05:09:08 +00007100 Diag(NewFD->getLocation(),
7101 diag::err_explicit_specialization_inconsistent_storage_class)
7102 << SC
7103 << FixItHint::CreateRemoval(
7104 D.getDeclSpec().getStorageClassSpecLoc());
7105
7106 else
7107 Diag(NewFD->getLocation(),
7108 diag::ext_explicit_specialization_storage_class)
7109 << FixItHint::CreateRemoval(
7110 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregore885e182011-05-21 18:53:30 +00007111 }
7112
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007113 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7114 if (CheckMemberSpecialization(NewFD, Previous))
7115 NewFD->setInvalidDecl();
7116 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007117
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007118 // Perform semantic checking on the function declaration.
David Blaikie14068e82011-09-08 06:33:04 +00007119 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemerc371db62013-07-06 02:13:46 +00007120 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7121 CheckMain(NewFD, D.getDeclSpec());
7122
David Majnemere9f6f332013-09-16 22:44:20 +00007123 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7124 CheckMSVCRTEntryPoint(NewFD);
7125
David Blaikie14068e82011-09-08 06:33:04 +00007126 if (NewFD->isInvalidDecl()) {
7127 // If this is a class member, mark the class invalid immediately.
7128 // This avoids some consistency errors later.
7129 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7130 methodDecl->getParent()->setInvalidDecl();
David Majnemerc371db62013-07-06 02:13:46 +00007131 } else
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007132 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7133 isExplicitSpecialization));
David Blaikie14068e82011-09-08 06:33:04 +00007134 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007135
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007136 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007137 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7138 "previous declaration set still overloaded");
7139
7140 NamedDecl *PrincipalDecl = (FunctionTemplate
7141 ? cast<NamedDecl>(FunctionTemplate)
7142 : NewFD);
7143
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007144 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007145 AccessSpecifier Access = AS_public;
7146 if (!NewFD->isInvalidDecl())
Douglas Gregoref96ee02012-01-14 16:38:05 +00007147 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007148
7149 NewFD->setAccess(Access);
7150 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007151 }
7152
7153 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7154 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7155 PrincipalDecl->setNonMemberOperator();
7156
7157 // If we have a function template, check the template parameter
7158 // list. This will check and merge default template arguments.
7159 if (FunctionTemplate) {
David Blaikied662a792011-10-19 22:56:21 +00007160 FunctionTemplateDecl *PrevTemplate =
Douglas Gregoref96ee02012-01-14 16:38:05 +00007161 FunctionTemplate->getPreviousDecl();
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007162 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikied662a792011-10-19 22:56:21 +00007163 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00007164 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007165 ? (D.isFunctionDefinition()
Douglas Gregord89d86f2011-02-04 04:20:44 +00007166 ? TPC_FriendFunctionTemplateDefinition
7167 : TPC_FriendFunctionTemplate)
7168 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00007169 DC && DC->isRecord() &&
7170 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00007171 ? TPC_ClassTemplateMember
7172 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007173 }
7174
7175 if (NewFD->isInvalidDecl()) {
7176 // Ignore all the rest of this.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007177 } else if (!D.isRedeclaration()) {
Kaelyn Uhrainf09ce392011-10-11 00:28:52 +00007178 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007179 AddToScope };
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007180 // Fake up an access specifier if it's supposed to be a class member.
7181 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7182 NewFD->setAccess(AS_public);
7183
7184 // Qualified decls generally require a previous declaration.
7185 if (D.getCXXScopeSpec().isSet()) {
7186 // ...with the major exception of templated-scope or
7187 // dependent-scope friend declarations.
7188
7189 // TODO: we currently also suppress this check in dependent
7190 // contexts because (1) the parameter depth will be off when
7191 // matching friend templates and (2) we might actually be
7192 // selecting a friend based on a dependent factor. But there
7193 // are situations where these conditions don't apply and we
7194 // can actually do this check immediately.
7195 if (isFriend &&
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00007196 (TemplateParamLists.size() ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007197 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7198 CurContext->isDependentContext())) {
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007199 // ignore these
7200 } else {
7201 // The user tried to provide an out-of-line definition for a
7202 // function that is a member of a class or namespace, but there
7203 // was no such member function declared (C++ [class.mfct]p2,
7204 // C++ [namespace.memdef]p2). For example:
7205 //
7206 // class X {
7207 // void f() const;
7208 // };
7209 //
7210 // void X::f() { } // ill-formed
7211 //
7212 // Complain about this problem, and attempt to suggest close
7213 // matches (e.g., those that differ only in cv-qualifiers and
7214 // whether the parameter types are references).
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007215
Richard Smith4e9686b2013-08-09 04:35:01 +00007216 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7217 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007218 AddToScope = ExtraArgs.AddToScope;
7219 return Result;
7220 }
Chandler Carruth47eb2b62011-08-19 01:38:33 +00007221 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007222
7223 // Unqualified local friend declarations are required to resolve
7224 // to something.
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007225 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith4e9686b2013-08-09 04:35:01 +00007226 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7227 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain2afd7662011-10-11 00:28:39 +00007228 AddToScope = ExtraArgs.AddToScope;
7229 return Result;
7230 }
Chandler Carruth3d095fe2011-08-19 01:40:11 +00007231 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007232
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007233 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007234 !isFriend && !isFunctionTemplateSpecialization &&
Sean Hunte4246a62011-05-12 06:15:49 +00007235 !isExplicitSpecialization) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007236 // An out-of-line member function declaration must also be a
7237 // definition (C++ [dcl.meaning]p1).
7238 // Note that this is not the case for explicit specializations of
7239 // function templates or member functions of class templates, per
David Blaikied662a792011-10-19 22:56:21 +00007240 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7241 // extension for compatibility with old SWIG code which likes to
7242 // generate them.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007243 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7244 << D.getCXXScopeSpec().getRange();
7245 }
7246 }
Ryan Flynn478fbc62009-07-25 22:29:44 +00007247
Rafael Espindola65611bf2013-03-02 21:41:48 +00007248 ProcessPragmaWeak(S, NewFD);
Rafael Espindola2a5bb502013-01-16 23:11:15 +00007249 checkAttributesAfterMerging(*this, *NewFD);
7250
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007251 AddKnownFunctionAttributes(NewFD);
7252
Douglas Gregord9455382010-08-06 13:50:58 +00007253 if (NewFD->hasAttr<OverloadableAttr>() &&
7254 !NewFD->getType()->getAs<FunctionProtoType>()) {
7255 Diag(NewFD->getLocation(),
7256 diag::err_attribute_overloadable_no_prototype)
7257 << NewFD;
7258
7259 // Turn this into a variadic function with no parameters.
7260 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckneref072032013-08-27 23:08:25 +00007261 FunctionProtoType::ExtProtoInfo EPI(
7262 Context.getDefaultCallingConvention(true, false));
John McCalle23cf432010-12-14 08:05:40 +00007263 EPI.Variadic = true;
7264 EPI.ExtInfo = FT->getExtInfo();
7265
Dmitri Gribenko55431692013-05-05 00:41:58 +00007266 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00007267 NewFD->setType(R);
7268 }
7269
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007270 // If there's a #pragma GCC visibility in scope, and this isn't a class
7271 // member, set the visibility of this function.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007272 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007273 AddPushedVisibilityAttribute(NewFD);
7274
John McCall8dfac0b2011-09-30 05:12:12 +00007275 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7276 // marking the function.
7277 AddCFAuditedAttribute(NewFD);
7278
Richard Smithaa4bc182013-06-30 09:48:50 +00007279 // If this is the first declaration of an extern C variable, update
7280 // the map of such variables.
Rafael Espindola7693b322013-10-19 02:13:21 +00007281 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithaa4bc182013-06-30 09:48:50 +00007282 isIncompleteDeclExternC(*this, NewFD))
Richard Smith662f41b2013-06-18 20:15:12 +00007283 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007284
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007285 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007286 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00007287
David Blaikie4e4d0842012-03-11 07:00:24 +00007288 if (getLangOpts().CPlusPlus) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007289 if (FunctionTemplate) {
7290 if (NewFD->isInvalidDecl())
7291 FunctionTemplate->setInvalidDecl();
7292 return FunctionTemplate;
7293 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00007294 }
Mike Stump1eb44332009-09-09 15:08:12 +00007295
Guy Benyeie6b9d802013-01-20 12:31:11 +00007296 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyeie6b9d802013-01-20 12:31:11 +00007297 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7298 if ((getLangOpts().OpenCLVersion >= 120)
7299 && (SC == SC_Static)) {
7300 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7301 D.setInvalidType();
7302 }
Tanya Lattner7564bcc2013-01-30 19:48:52 +00007303
7304 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7305 if (!NewFD->getResultType()->isVoidType()) {
7306 Diag(D.getIdentifierLoc(),
7307 diag::err_expected_kernel_void_return_type);
7308 D.setInvalidType();
7309 }
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007310
7311 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyeie6b9d802013-01-20 12:31:11 +00007312 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7313 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly98f988d2013-01-29 10:54:06 +00007314 ParmVarDecl *Param = *PI;
Matt Arsenaulte6c8afc2013-07-23 01:23:36 +00007315 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyeie6b9d802013-01-20 12:31:11 +00007316 }
Tanya Lattner5e94d6f2012-06-19 23:09:52 +00007317 }
7318
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00007319 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007320
David Blaikie4e4d0842012-03-11 07:00:24 +00007321 if (getLangOpts().CUDA)
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007322 if (IdentifierInfo *II = NewFD->getIdentifier())
7323 if (!NewFD->isInvalidDecl() &&
7324 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7325 if (II->isStr("cudaConfigureCall")) {
7326 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7327 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7328
7329 Context.setcudaConfigureCallDecl(NewFD);
7330 }
7331 }
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007332
7333 // Here we have an function template explicit specialization at class scope.
7334 // The actually specialization will be postponed to template instatiation
7335 // time via the ClassScopeFunctionSpecializationDecl node.
7336 if (isDependentClassScopeExplicitSpecialization) {
7337 ClassScopeFunctionSpecializationDecl *NewSpec =
7338 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber6b020092012-06-25 17:21:05 +00007339 Context, CurContext, SourceLocation(),
7340 cast<CXXMethodDecl>(NewFD),
7341 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007342 CurContext->addDecl(NewSpec);
7343 AddToScope = false;
7344 }
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00007345
Douglas Gregor2dc0e642009-03-23 23:06:20 +00007346 return NewFD;
7347}
7348
7349/// \brief Perform semantic checking of a new function declaration.
7350///
7351/// Performs semantic analysis of the new function declaration
7352/// NewFD. This routine performs all semantic checking that does not
7353/// require the actual declarator involved in the declaration, and is
7354/// used both for the declaration of functions as they are parsed
7355/// (called via ActOnDeclarator) and for the declaration of functions
7356/// that have been instantiated via C++ template instantiation (called
7357/// via InstantiateDecl).
7358///
James Dennettefce31f2012-06-22 08:10:18 +00007359/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorfd056bc2009-10-13 16:30:37 +00007360/// an explicit specialization of the previous declaration.
7361///
Chris Lattnereaaebc72009-04-25 08:06:05 +00007362/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007363///
James Dennettefce31f2012-06-22 08:10:18 +00007364/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007365bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00007366 LookupResult &Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007367 bool IsExplicitSpecialization) {
David Blaikie14068e82011-09-08 06:33:04 +00007368 assert(!NewFD->getResultType()->isVariablyModifiedType()
7369 && "Variably modified return types are not handled here");
John McCall8c4859a2009-07-24 03:03:21 +00007370
Richard Smithdd9459f2013-08-13 18:18:50 +00007371 // Determine whether the type of this function should be merged with
7372 // a previous visible declaration. This never happens for functions in C++,
7373 // and always happens in C if the previous declaration was visible.
7374 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7375 !Previous.isShadowed();
7376
Douglas Gregor7dc80e12013-01-09 00:47:56 +00007377 // Filter out any non-conflicting previous declarations.
7378 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7379
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007380 bool Redeclaration = false;
Richard Smith21c8fa82013-01-14 05:37:29 +00007381 NamedDecl *OldDecl = 0;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007382
Douglas Gregor04495c82009-02-24 01:23:02 +00007383 // Merge or overload the declaration with an existing declaration of
7384 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00007385 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00007386 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007387 // a declaration that requires merging. If it's an overload,
7388 // there's no more work to do here; we'll just add the new
7389 // function to the scope.
John McCall871b2e72009-12-09 03:35:25 +00007390 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola90cc3902013-04-15 12:49:13 +00007391 NamedDecl *Candidate = Previous.getFoundDecl();
7392 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7393 Redeclaration = true;
7394 OldDecl = Candidate;
7395 }
John McCall871b2e72009-12-09 03:35:25 +00007396 } else {
John McCallad00b772010-06-16 08:42:20 +00007397 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7398 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00007399 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007400 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00007401 break;
7402
7403 case Ovl_NonFunction:
7404 Redeclaration = true;
7405 break;
7406
7407 case Ovl_Overload:
7408 Redeclaration = false;
7409 break;
John McCall68263142009-11-18 22:49:29 +00007410 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00007411
David Blaikie4e4d0842012-03-11 07:00:24 +00007412 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbournec80e8112011-01-21 02:08:54 +00007413 // If a function name is overloadable in C, then every function
7414 // with that name must be marked "overloadable".
7415 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7416 << Redeclaration << NewFD;
7417 NamedDecl *OverloadedDecl = 0;
7418 if (Redeclaration)
7419 OverloadedDecl = OldDecl;
7420 else if (!Previous.empty())
7421 OverloadedDecl = Previous.getRepresentativeDecl();
7422 if (OverloadedDecl)
7423 Diag(OverloadedDecl->getLocation(),
7424 diag::note_attribute_overloadable_prev_overload);
7425 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7426 Context));
7427 }
John McCall68263142009-11-18 22:49:29 +00007428 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007429 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007430
Richard Smithaa4bc182013-06-30 09:48:50 +00007431 // Check for a previous extern "C" declaration with this name.
7432 if (!Redeclaration &&
7433 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7434 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7435 if (!Previous.empty()) {
7436 // This is an extern "C" declaration with the same name as a previous
7437 // declaration, and thus redeclares that entity...
7438 Redeclaration = true;
7439 OldDecl = Previous.getFoundDecl();
Richard Smithdd9459f2013-08-13 18:18:50 +00007440 MergeTypeWithPrevious = false;
Richard Smithaa4bc182013-06-30 09:48:50 +00007441
7442 // ... except in the presence of __attribute__((overloadable)).
7443 if (OldDecl->hasAttr<OverloadableAttr>()) {
7444 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7445 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7446 << Redeclaration << NewFD;
7447 Diag(Previous.getFoundDecl()->getLocation(),
7448 diag::note_attribute_overloadable_prev_overload);
7449 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7450 Context));
7451 }
7452 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7453 Redeclaration = false;
7454 OldDecl = 0;
7455 }
7456 }
7457 }
7458 }
7459
Richard Smith21c8fa82013-01-14 05:37:29 +00007460 // C++11 [dcl.constexpr]p8:
7461 // A constexpr specifier for a non-static member function that is not
7462 // a constructor declares that member function to be const.
7463 //
7464 // This needs to be delayed until we know whether this is an out-of-line
7465 // definition of a static member function.
Richard Smith84046262013-04-21 01:08:50 +00007466 //
7467 // This rule is not present in C++1y, so we produce a backwards
7468 // compatibility warning whenever it happens in C++11.
Richard Smith21c8fa82013-01-14 05:37:29 +00007469 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith84046262013-04-21 01:08:50 +00007470 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7471 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith21c8fa82013-01-14 05:37:29 +00007472 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7473 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7474 if (FunctionTemplateDecl *OldTD =
7475 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7476 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7477 if (!OldMD || !OldMD->isStatic()) {
7478 const FunctionProtoType *FPT =
7479 MD->getType()->castAs<FunctionProtoType>();
7480 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7481 EPI.TypeQuals |= Qualifiers::Const;
7482 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00007483 FPT->getArgTypes(), EPI));
Richard Smith84046262013-04-21 01:08:50 +00007484
7485 // Warn that we did this, if we're not performing template instantiation.
7486 // In that case, we'll have warned already when the template was defined.
7487 if (ActiveTemplateInstantiations.empty()) {
7488 SourceLocation AddConstLoc;
7489 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7490 .IgnoreParens().getAs<FunctionTypeLoc>())
7491 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7492
7493 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7494 << FixItHint::CreateInsertion(AddConstLoc, " const");
7495 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007496 }
7497 }
7498
7499 if (Redeclaration) {
7500 // NewFD and OldDecl represent declarations that need to be
7501 // merged.
Richard Smithdd9459f2013-08-13 18:18:50 +00007502 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith21c8fa82013-01-14 05:37:29 +00007503 NewFD->setInvalidDecl();
7504 return Redeclaration;
7505 }
7506
7507 Previous.clear();
7508 Previous.addDecl(OldDecl);
7509
7510 if (FunctionTemplateDecl *OldTemplateDecl
7511 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7512 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7513 FunctionTemplateDecl *NewTemplateDecl
7514 = NewFD->getDescribedFunctionTemplate();
7515 assert(NewTemplateDecl && "Template/non-template mismatch");
7516 if (CXXMethodDecl *Method
7517 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7518 Method->setAccess(OldTemplateDecl->getAccess());
7519 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007520 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007521
7522 // If this is an explicit specialization of a member that is a function
7523 // template, mark it as a member specialization.
7524 if (IsExplicitSpecialization &&
7525 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7526 NewTemplateDecl->setMemberSpecialization();
7527 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00007528 }
Richard Smith21c8fa82013-01-14 05:37:29 +00007529
7530 } else {
John McCalld5617ee2013-01-25 22:31:03 +00007531 // This needs to happen first so that 'inline' propagates.
Richard Smith21c8fa82013-01-14 05:37:29 +00007532 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCalld5617ee2013-01-25 22:31:03 +00007533
7534 if (isa<CXXMethodDecl>(NewFD)) {
7535 // A valid redeclaration of a C++ method must be out-of-line,
7536 // but (unfortunately) it's not necessarily a definition
7537 // because of templates, which means that the previous
7538 // declaration is not necessarily from the class definition.
7539
7540 // For just setting the access, that doesn't matter.
7541 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7542 NewFD->setAccess(oldMethod->getAccess());
7543
7544 // Update the key-function state if necessary for this ABI.
7545 if (NewFD->isInlined() &&
7546 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7547 // setNonKeyFunction needs to work with the original
7548 // declaration from the class definition, and isVirtual() is
7549 // just faster in that case, so map back to that now.
Rafael Espindolabc650912013-10-17 15:37:26 +00007550 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCalld5617ee2013-01-25 22:31:03 +00007551 if (oldMethod->isVirtual()) {
7552 Context.setNonKeyFunction(oldMethod);
7553 }
7554 }
7555 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007556 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00007557 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007558
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007559 // Semantic checking for this function declaration (in isolation).
David Blaikie4e4d0842012-03-11 07:00:24 +00007560 if (getLangOpts().CPlusPlus) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007561 // C++-specific checks.
7562 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7563 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00007564 } else if (CXXDestructorDecl *Destructor =
7565 dyn_cast<CXXDestructorDecl>(NewFD)) {
7566 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007567 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00007568
Douglas Gregor4923aa22010-07-02 20:37:36 +00007569 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00007570 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007571 if (!ClassType->isDependentType()) {
7572 DeclarationName Name
7573 = Context.DeclarationNames.getCXXDestructorName(
7574 Context.getCanonicalType(ClassType));
7575 if (NewFD->getDeclName() != Name) {
7576 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007577 NewFD->setInvalidDecl();
7578 return Redeclaration;
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007579 }
7580 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007581 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00007582 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007583 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00007584 }
7585
7586 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00007587 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7588 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00007589 !Method->getDescribedFunctionTemplate() &&
7590 Method->isCanonicalDecl()) {
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007591 if (AddOverriddenMethods(Method->getParent(), Method)) {
7592 // If the function was marked as "static", we have a problem.
7593 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie5708c182012-10-17 00:47:58 +00007594 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007595 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00007596 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00007597 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +00007598
7599 if (Method->isStatic())
7600 checkThisInStaticMemberFunctionType(Method);
Douglas Gregore6342c02009-12-01 17:35:23 +00007601 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007602
7603 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7604 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007605 CheckOverloadedOperatorDeclaration(NewFD)) {
7606 NewFD->setInvalidDecl();
7607 return Redeclaration;
7608 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007609
7610 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7611 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007612 CheckLiteralOperatorDeclaration(NewFD)) {
7613 NewFD->setInvalidDecl();
7614 return Redeclaration;
7615 }
Sean Hunta6c058d2010-01-13 09:01:02 +00007616
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007617 // In C++, check default arguments now that we have merged decls. Unless
7618 // the lexical context is the class, because in this case this is done
7619 // during delayed parsing anyway.
7620 if (!CurContext->isRecord())
7621 CheckCXXDefaultArguments(NewFD);
Warren Hunt2d023ec2013-11-01 23:46:51 +00007622
Douglas Gregorb68e3992010-12-21 19:47:46 +00007623 // If this function declares a builtin function, check the type of this
7624 // declaration against the expected type for the builtin.
7625 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7626 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanian9ef15182013-01-05 21:54:55 +00007627 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregorb68e3992010-12-21 19:47:46 +00007628 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7629 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7630 // The type of this function differs from the type of the builtin,
7631 // so forget about the builtin entirely.
7632 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7633 }
7634 }
Warren Hunt2d023ec2013-11-01 23:46:51 +00007635
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007636 // If this function is declared as being extern "C", then check to see if
7637 // the function returns a UDT (class, struct, or union type) that is not C
7638 // compatible, and if it does, warn the user.
Fariborz Jahanian96db3292013-03-14 23:09:00 +00007639 // But, issue any diagnostic on the first declaration only.
7640 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007641 QualType R = NewFD->getResultType();
Hans Wennborg168c07b2012-07-24 17:59:41 +00007642 if (R->isIncompleteType() && !R->isVoidType())
7643 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7644 << NewFD << R;
Douglas Gregorb38b4912012-08-07 06:14:34 +00007645 else if (!R.isPODType(Context) && !R->isVoidType() &&
7646 !R->isObjCObjectPointerType())
Hans Wennborg168c07b2012-07-24 17:59:41 +00007647 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballman2c0bf242012-02-09 01:21:34 +00007648 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00007649 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00007650 return Redeclaration;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00007651}
7652
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007653static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7654 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7655 if (!TSI)
7656 return SourceRange();
7657
7658 TypeLoc TL = TSI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00007659 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007660 if (!FunctionTL)
7661 return SourceRange();
7662
David Blaikie39e6ab42013-02-18 22:06:02 +00007663 TypeLoc ResultTL = FunctionTL.getResultLoc();
7664 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007665 return ResultTL.getSourceRange();
7666
7667 return SourceRange();
7668}
7669
David Blaikie14068e82011-09-08 06:33:04 +00007670void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smitha5065862012-02-04 06:10:17 +00007671 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7672 // static or constexpr is ill-formed.
Richard Smithde03c152013-01-17 22:16:11 +00007673 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7674 // appear in a declaration of main.
John McCall13591ed2009-07-25 04:36:53 +00007675 // static main is not an error under C99, but we should warn about it.
Richard Smithde03c152013-01-17 22:16:11 +00007676 // We accept _Noreturn main as an extension.
David Blaikie14068e82011-09-08 06:33:04 +00007677 if (FD->getStorageClass() == SC_Static)
David Blaikie4e4d0842012-03-11 07:00:24 +00007678 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikie14068e82011-09-08 06:33:04 +00007679 ? diag::err_static_main : diag::warn_static_main)
7680 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7681 if (FD->isInlineSpecified())
7682 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7683 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko445743d2013-01-21 11:25:03 +00007684 if (DS.isNoreturnSpecified()) {
7685 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7686 SourceRange NoreturnRange(NoreturnLoc,
7687 PP.getLocForEndOfToken(NoreturnLoc));
7688 Diag(NoreturnLoc, diag::ext_noreturn_main);
7689 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7690 << FixItHint::CreateRemoval(NoreturnRange);
7691 }
Richard Smitha5065862012-02-04 06:10:17 +00007692 if (FD->isConstexpr()) {
7693 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7694 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7695 FD->setConstexpr(false);
7696 }
John McCall13591ed2009-07-25 04:36:53 +00007697
Joey Goulyc879fe52013-11-05 12:30:39 +00007698 if (getLangOpts().OpenCL) {
7699 Diag(FD->getLocation(), diag::err_opencl_no_main)
7700 << FD->hasAttr<OpenCLKernelAttr>();
7701 FD->setInvalidDecl();
7702 return;
7703 }
7704
John McCall13591ed2009-07-25 04:36:53 +00007705 QualType T = FD->getType();
7706 assert(T->isFunctionType() && "function decl is not of function type");
John McCall75d8ba32012-02-14 19:50:52 +00007707 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007708
John McCall75d8ba32012-02-14 19:50:52 +00007709 // All the standards say that main() should should return 'int'.
7710 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7711 // In C and C++, main magically returns 0 if you fall off the end;
7712 // set the flag which tells us that.
7713 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7714 FD->setHasImplicitReturnZero(true);
7715
7716 // In C with GNU extensions we allow main() to have non-integer return
7717 // type, but we should warn about the extension, and we disable the
7718 // implicit-return-zero rule.
David Blaikie4e4d0842012-03-11 07:00:24 +00007719 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall75d8ba32012-02-14 19:50:52 +00007720 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7721
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007722 SourceRange ResultRange = getResultSourceRange(FD);
7723 if (ResultRange.isValid())
7724 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7725 << FixItHint::CreateReplacement(ResultRange, "int");
7726
John McCall75d8ba32012-02-14 19:50:52 +00007727 // Otherwise, this is just a flat-out error.
7728 } else {
Dmitri Gribenkoa6f97072013-01-17 00:26:13 +00007729 SourceRange ResultRange = getResultSourceRange(FD);
7730 if (ResultRange.isValid())
7731 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7732 << FixItHint::CreateReplacement(ResultRange, "int");
7733 else
7734 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7735
John McCall13591ed2009-07-25 04:36:53 +00007736 FD->setInvalidDecl(true);
7737 }
7738
7739 // Treat protoless main() as nullary.
7740 if (isa<FunctionNoProtoType>(FT)) return;
7741
7742 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7743 unsigned nparams = FTP->getNumArgs();
7744 assert(FD->getNumParams() == nparams);
7745
John McCall66755862009-12-24 09:58:38 +00007746 bool HasExtraParameters = (nparams > 3);
7747
7748 // Darwin passes an undocumented fourth argument of type char**. If
7749 // other platforms start sprouting these, the logic below will start
7750 // getting shifty.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00007751 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall66755862009-12-24 09:58:38 +00007752 HasExtraParameters = false;
7753
7754 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00007755 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7756 FD->setInvalidDecl(true);
7757 nparams = 3;
7758 }
7759
7760 // FIXME: a lot of the following diagnostics would be improved
7761 // if we had some location information about types.
7762
7763 QualType CharPP =
7764 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00007765 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00007766
7767 for (unsigned i = 0; i < nparams; ++i) {
7768 QualType AT = FTP->getArgType(i);
7769
7770 bool mismatch = true;
7771
7772 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7773 mismatch = false;
7774 else if (Expected[i] == CharPP) {
7775 // As an extension, the following forms are okay:
7776 // char const **
7777 // char const * const *
7778 // char * const *
7779
John McCall0953e762009-09-24 19:53:00 +00007780 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00007781 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00007782 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7783 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith485b3122013-01-29 02:49:47 +00007784 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7785 Context.CharTy)) {
John McCall13591ed2009-07-25 04:36:53 +00007786 qs.removeConst();
7787 mismatch = !qs.empty();
7788 }
7789 }
7790
7791 if (mismatch) {
7792 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7793 // TODO: suggest replacing given type with expected type
7794 FD->setInvalidDecl(true);
7795 }
7796 }
7797
7798 if (nparams == 1 && !FD->isInvalidDecl()) {
7799 Diag(FD->getLocation(), diag::warn_main_one_arg);
7800 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007801
7802 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemere9f6f332013-09-16 22:44:20 +00007803 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7804 FD->setInvalidDecl();
7805 }
7806}
7807
7808void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7809 QualType T = FD->getType();
7810 assert(T->isFunctionType() && "function decl is not of function type");
7811 const FunctionType *FT = T->castAs<FunctionType>();
7812
7813 // Set an implicit return of 'zero' if the function can return some integral,
7814 // enumeration, pointer or nullptr type.
7815 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7816 FT->getResultType()->isAnyPointerType() ||
7817 FT->getResultType()->isNullPtrType())
7818 // DllMain is exempt because a return value of zero means it failed.
7819 if (FD->getName() != "DllMain")
7820 FD->setHasImplicitReturnZero(true);
7821
7822 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7823 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregor0bab54c2010-10-21 16:57:46 +00007824 FD->setInvalidDecl();
7825 }
John McCall8c4859a2009-07-24 03:03:21 +00007826}
7827
Eli Friedmanc594b322008-05-20 13:48:25 +00007828bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00007829 // FIXME: Need strict checking. In C89, we need to check for
7830 // any assignment, increment, decrement, function-calls, or
7831 // commas outside of a sizeof. In C99, it's the same list,
7832 // except that the aforementioned are allowed in unevaluated
7833 // expressions. Everything else falls under the
7834 // "may accept other forms of constant expressions" exception.
7835 // (We never end up here for C++, so the constant expression
7836 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00007837 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00007838 return false;
Eli Friedman21298282009-02-26 04:47:58 +00007839 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7840 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00007841 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00007842}
7843
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007844namespace {
7845 // Visits an initialization expression to see if OrigDecl is evaluated in
7846 // its own initialization and throws a warning if it does.
7847 class SelfReferenceChecker
7848 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7849 Sema &S;
7850 Decl *OrigDecl;
Richard Trieu898267f2011-09-01 21:44:13 +00007851 bool isRecordType;
7852 bool isPODType;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007853 bool isReferenceType;
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007854
7855 public:
7856 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7857
7858 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieu898267f2011-09-01 21:44:13 +00007859 S(S), OrigDecl(OrigDecl) {
7860 isPODType = false;
7861 isRecordType = false;
Hans Wennborg8be9e772012-08-17 10:12:33 +00007862 isReferenceType = false;
Richard Trieu898267f2011-09-01 21:44:13 +00007863 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7864 isPODType = VD->getType().isPODType(S.Context);
7865 isRecordType = VD->getType()->isRecordType();
Hans Wennborg8be9e772012-08-17 10:12:33 +00007866 isReferenceType = VD->getType()->isReferenceType();
Richard Trieu898267f2011-09-01 21:44:13 +00007867 }
7868 }
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007869
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007870 // For most expressions, the cast is directly above the DeclRefExpr.
7871 // For conditional operators, the cast can be outside the conditional
7872 // operator if both expressions are DeclRefExpr's.
7873 void HandleValue(Expr *E) {
Richard Trieu568f7852012-10-01 17:39:51 +00007874 if (isReferenceType)
7875 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007876 E = E->IgnoreParenImpCasts();
7877 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7878 HandleDeclRefExpr(DRE);
7879 return;
7880 }
7881
7882 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7883 HandleValue(CO->getTrueExpr());
7884 HandleValue(CO->getFalseExpr());
Richard Trieu6b2cc422012-10-03 00:41:36 +00007885 return;
7886 }
7887
7888 if (isa<MemberExpr>(E)) {
7889 Expr *Base = E->IgnoreParenImpCasts();
7890 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7891 // Check for static member variables and don't warn on them.
7892 if (!isa<FieldDecl>(ME->getMemberDecl()))
7893 return;
7894 Base = ME->getBase()->IgnoreParenImpCasts();
7895 }
7896 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7897 HandleDeclRefExpr(DRE);
7898 return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007899 }
7900 }
7901
Richard Trieu568f7852012-10-01 17:39:51 +00007902 // Reference types are handled here since all uses of references are
7903 // bad, not just r-value uses.
7904 void VisitDeclRefExpr(DeclRefExpr *E) {
7905 if (isReferenceType)
7906 HandleDeclRefExpr(E);
7907 }
7908
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007909 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu6b2cc422012-10-03 00:41:36 +00007910 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007911 (isRecordType && E->getCastKind() == CK_NoOp))
7912 HandleValue(E->getSubExpr());
7913
7914 Inherited::VisitImplicitCastExpr(E);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007915 }
7916
Richard Trieu898267f2011-09-01 21:44:13 +00007917 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007918 // Don't warn on arrays since they can be treated as pointers.
Richard Trieu47eb8982011-09-07 00:58:53 +00007919 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007920
Richard Trieu6b2cc422012-10-03 00:41:36 +00007921 // Warn when a non-static method call is followed by non-static member
7922 // field accesses, which is followed by a DeclRefExpr.
7923 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7924 bool Warn = (MD && !MD->isStatic());
7925 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7926 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7927 if (!isa<FieldDecl>(ME->getMemberDecl()))
7928 Warn = false;
7929 Base = ME->getBase()->IgnoreParenImpCasts();
7930 }
Richard Trieu898267f2011-09-01 21:44:13 +00007931
Richard Trieu6b2cc422012-10-03 00:41:36 +00007932 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7933 if (Warn)
7934 HandleDeclRefExpr(DRE);
7935 return;
7936 }
7937
7938 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7939 // Visit that expression.
7940 Visit(Base);
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007941 }
7942
Richard Trieu8af742a2013-03-26 03:41:40 +00007943 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7944 if (E->getNumArgs() > 0)
7945 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7946 HandleDeclRefExpr(DRE);
7947
7948 Inherited::VisitCXXOperatorCallExpr(E);
7949 }
7950
Richard Trieu898267f2011-09-01 21:44:13 +00007951 void VisitUnaryOperator(UnaryOperator *E) {
7952 // For POD record types, addresses of its own members are well-defined.
Richard Trieu6b2cc422012-10-03 00:41:36 +00007953 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7954 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7955 if (!isPODType)
7956 HandleValue(E->getSubExpr());
7957 return;
7958 }
Richard Trieu898267f2011-09-01 21:44:13 +00007959 Inherited::VisitUnaryOperator(E);
Richard Smith0f2fc5f2013-05-03 19:16:22 +00007960 }
Richard Trieu7e9f8af2012-05-09 00:21:34 +00007961
7962 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7963
Richard Trieu898267f2011-09-01 21:44:13 +00007964 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumif3052792013-01-19 01:54:35 +00007965 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007966 if (OrigDecl != ReferenceDecl) return;
Ted Kremenek39371b82013-01-19 04:33:14 +00007967 unsigned diag;
7968 if (isReferenceType) {
7969 diag = diag::warn_uninit_self_reference_in_reference_init;
7970 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7971 diag = diag::warn_static_self_reference_in_init;
7972 } else {
7973 diag = diag::warn_uninit_self_reference_in_init;
7974 }
7975
Richard Trieu898267f2011-09-01 21:44:13 +00007976 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborg5965b7c2012-08-20 08:52:22 +00007977 S.PDiag(diag)
Hans Wennborg7821e072012-09-21 08:58:33 +00007978 << DRE->getNameInfo().getName()
Douglas Gregor63fe6812011-05-24 16:02:01 +00007979 << OrigDecl->getLocation()
Richard Trieu898267f2011-09-01 21:44:13 +00007980 << DRE->getSourceRange());
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007981 }
7982 };
Chandler Carrutha7689ef2011-03-27 09:46:56 +00007983
Richard Trieu568f7852012-10-01 17:39:51 +00007984 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7985 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7986 bool DirectInit) {
7987 // Parameters arguments are occassionially constructed with itself,
7988 // for instance, in recursive functions. Skip them.
7989 if (isa<ParmVarDecl>(OrigDecl))
7990 return;
7991
7992 E = E->IgnoreParens();
7993
7994 // Skip checking T a = a where T is not a record or reference type.
7995 // Doing so is a way to silence uninitialized warnings.
7996 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7997 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7998 if (ICE->getCastKind() == CK_LValueToRValue)
7999 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8000 if (DRE->getDecl() == OrigDecl)
8001 return;
8002
8003 SelfReferenceChecker(S, OrigDecl).Visit(E);
8004 }
Richard Trieu898267f2011-09-01 21:44:13 +00008005}
8006
Douglas Gregor09f41cf2009-01-14 15:45:31 +00008007/// AddInitializerToDecl - Adds the initializer Init to the
8008/// declaration dcl. If DirectInit is true, this is C++ direct
8009/// initialization rather than copy initialization.
Richard Smith34b41d92011-02-20 03:19:35 +00008010void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8011 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008012 // If there is no declaration, there was an error parsing it. Just ignore
8013 // the initializer.
Richard Smith34b41d92011-02-20 03:19:35 +00008014 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner9a11b9a2007-10-19 20:10:30 +00008015 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008016
Douglas Gregor021c3b32009-03-11 23:00:04 +00008017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8018 // With declarators parsed the way they are, the parser cannot
8019 // distinguish between a normal initializer and a pure-specifier.
8020 // Thus this grotesque test.
8021 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00008022 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00008023 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8024 CheckPureMethod(Method, Init->getSourceRange());
8025 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00008026 Diag(Method->getLocation(), diag::err_member_function_initialization)
8027 << Method->getDeclName() << Init->getSourceRange();
8028 Method->setInvalidDecl();
8029 }
8030 return;
8031 }
8032
Steve Naroff410e3e22007-09-12 20:13:48 +00008033 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8034 if (!VDecl) {
Richard Smithc2cdd532011-06-12 11:43:46 +00008035 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8036 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00008037 RealDecl->setInvalidDecl();
8038 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00008039 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008040 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8041
Richard Smith01888722011-12-15 19:20:59 +00008042 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00008043 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008044 Expr *DeduceInit = Init;
8045 // Initializer could be a C++ direct-initializer. Deduction only works if it
8046 // contains exactly one expression.
8047 if (CXXDirectInit) {
8048 if (CXXDirectInit->getNumExprs() == 0) {
8049 // It isn't possible to write this directly, but it is possible to
8050 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar96a00142012-03-09 18:35:03 +00008051 Diag(CXXDirectInit->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008052 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8053 : diag::err_auto_var_init_no_expression)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008054 << VDecl->getDeclName() << VDecl->getType()
8055 << VDecl->getSourceRange();
8056 RealDecl->setInvalidDecl();
8057 return;
8058 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00008059 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smith04fa7a32013-09-28 04:02:39 +00008060 VDecl->isInitCapture()
8061 ? diag::err_init_capture_multiple_expressions
8062 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008063 << VDecl->getDeclName() << VDecl->getType()
8064 << VDecl->getSourceRange();
8065 RealDecl->setInvalidDecl();
8066 return;
8067 } else {
8068 DeduceInit = CXXDirectInit->getExpr(0);
8069 }
8070 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008071
8072 // Expressions default to 'id' when we're in a debugger.
8073 bool DefaultedToAuto = false;
8074 if (getLangOpts().DebuggerCastResultToId &&
8075 Init->getType() == Context.UnknownAnyTy) {
8076 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8077 if (Result.isInvalid()) {
8078 VDecl->setInvalidDecl();
8079 return;
8080 }
8081 Init = Result.take();
8082 DefaultedToAuto = true;
8083 }
Richard Smith9b131752013-04-30 21:23:01 +00008084
8085 QualType DeducedType;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008086 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00008087 DAR_Failed)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008088 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith9b131752013-04-30 21:23:01 +00008089 if (DeducedType.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008090 RealDecl->setInvalidDecl();
8091 return;
8092 }
Richard Smith9b131752013-04-30 21:23:01 +00008093 VDecl->setType(DeducedType);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00008094 assert(VDecl->isLinkageValid());
Rafael Espindola2d9e8832013-03-12 21:06:00 +00008095
John McCallf85e1932011-06-15 23:02:42 +00008096 // In ARC, infer lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00008097 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCallf85e1932011-06-15 23:02:42 +00008098 VDecl->setInvalidDecl();
8099
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008100 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8101 // 'id' instead of a specific object type prevents most of our usual checks.
8102 // We only want to warn outside of template instantiations, though:
8103 // inside a template, the 'id' could have come from a parameter.
Douglas Gregor1344e942013-03-07 22:57:58 +00008104 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith9b131752013-04-30 21:23:01 +00008105 DeducedType->isObjCIdType()) {
8106 SourceLocation Loc =
8107 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rose0abbdfe2012-06-08 22:46:07 +00008108 Diag(Loc, diag::warn_auto_var_is_id)
8109 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8110 }
8111
Richard Smith34b41d92011-02-20 03:19:35 +00008112 // If this is a redeclaration, check that the type we just deduced matches
8113 // the previously declared type.
Richard Smithdd9459f2013-08-13 18:18:50 +00008114 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8115 // We never need to merge the type, because we cannot form an incomplete
8116 // array of auto, nor deduce such a type.
8117 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8118 }
Richard Smithdc7a4f52013-04-30 13:56:41 +00008119
8120 // Check the deduced type is valid for a variable declaration.
8121 CheckVariableDeclarationType(VDecl);
8122 if (VDecl->isInvalidDecl())
8123 return;
Richard Smith34b41d92011-02-20 03:19:35 +00008124 }
Richard Smith01888722011-12-15 19:20:59 +00008125
8126 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8127 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8128 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8129 VDecl->setInvalidDecl();
8130 return;
8131 }
8132
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008133 if (!VDecl->getType()->isDependentType()) {
8134 // A definition must end up with a complete type, which means it must be
8135 // complete with the restriction that an array type might be completed by
8136 // the initializer; note that later code assumes this restriction.
8137 QualType BaseDeclType = VDecl->getType();
8138 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8139 BaseDeclType = Array->getElementType();
8140 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8141 diag::err_typecheck_decl_incomplete_type)) {
8142 RealDecl->setInvalidDecl();
8143 return;
8144 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008145
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008146 // The variable can not have an abstract class type.
8147 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8148 diag::err_abstract_type_in_decl,
8149 AbstractVariableType))
8150 VDecl->setInvalidDecl();
Eli Friedmana31feca2009-04-13 21:28:54 +00008151 }
8152
Sebastian Redl31310a22010-02-01 20:16:42 +00008153 const VarDecl *Def;
8154 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00008155 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00008156 << VDecl->getDeclName();
8157 Diag(Def->getLocation(), diag::note_previous_definition);
8158 VDecl->setInvalidDecl();
8159 return;
8160 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008161
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008162 const VarDecl* PrevInit = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00008163 if (getLangOpts().CPlusPlus) {
Douglas Gregora31040f2010-12-16 01:31:22 +00008164 // C++ [class.static.data]p4
8165 // If a static data member is of const integral or const
8166 // enumeration type, its declaration in the class definition can
8167 // specify a constant-initializer which shall be an integral
8168 // constant expression (5.19). In that case, the member can appear
8169 // in integral constant expressions. The member shall still be
8170 // defined in a namespace scope if it is used in the program and the
8171 // namespace scope definition shall not contain an initializer.
8172 //
8173 // We already performed a redefinition check above, but for static
8174 // data members we also need to check whether there was an in-class
8175 // declaration with an initializer.
8176 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
David Blaikied662a792011-10-19 22:56:21 +00008177 Diag(VDecl->getLocation(), diag::err_redefinition)
8178 << VDecl->getDeclName();
Douglas Gregora31040f2010-12-16 01:31:22 +00008179 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8180 return;
8181 }
Douglas Gregor275a3692009-03-10 23:43:53 +00008182
Douglas Gregora31040f2010-12-16 01:31:22 +00008183 if (VDecl->hasLocalStorage())
8184 getCurFunction()->setHasBranchProtectedScope();
8185
8186 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8187 VDecl->setInvalidDecl();
8188 return;
8189 }
8190 }
John McCalle46f62c2010-08-01 01:24:59 +00008191
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008192 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8193 // a kernel function cannot be initialized."
8194 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8195 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8196 VDecl->setInvalidDecl();
8197 return;
8198 }
8199
Steve Naroffbb204692007-09-12 14:07:44 +00008200 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00008201 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00008202 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008203
Douglas Gregor1344e942013-03-07 22:57:58 +00008204 // Expressions default to 'id' when we're in a debugger
8205 // and we are assigning it to a variable of Objective-C pointer type.
8206 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8207 Init->getType() == Context.UnknownAnyTy) {
8208 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8209 if (Result.isInvalid()) {
8210 VDecl->setInvalidDecl();
8211 return;
Fariborz Jahanian509fb3e2012-03-09 18:47:16 +00008212 }
Douglas Gregor1344e942013-03-07 22:57:58 +00008213 Init = Result.take();
8214 }
Richard Smith01888722011-12-15 19:20:59 +00008215
8216 // Perform the initialization.
8217 if (!VDecl->isInvalidDecl()) {
8218 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8219 InitializationKind Kind
Sebastian Redl168319c2012-02-12 16:37:24 +00008220 = DirectInit ?
8221 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8222 Init->getLocStart(),
8223 Init->getLocEnd())
8224 : InitializationKind::CreateDirectList(
8225 VDecl->getLocation())
Richard Smith01888722011-12-15 19:20:59 +00008226 : InitializationKind::CreateCopy(VDecl->getLocation(),
8227 Init->getLocStart());
8228
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00008229 MultiExprArg Args = Init;
8230 if (CXXDirectInit)
8231 Args = MultiExprArg(CXXDirectInit->getExprs(),
8232 CXXDirectInit->getNumExprs());
8233
8234 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8235 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith01888722011-12-15 19:20:59 +00008236 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00008237 VDecl->setInvalidDecl();
Richard Smith01888722011-12-15 19:20:59 +00008238 return;
Steve Naroffbb204692007-09-12 14:07:44 +00008239 }
Richard Smith01888722011-12-15 19:20:59 +00008240
8241 Init = Result.takeAs<Expr>();
8242 }
8243
Richard Trieu568f7852012-10-01 17:39:51 +00008244 // Check for self-references within variable initializers.
8245 // Variables declared within a function/method body (except for references)
8246 // are handled by a dataflow analysis.
8247 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8248 VDecl->getType()->isReferenceType()) {
8249 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8250 }
8251
Richard Smith01888722011-12-15 19:20:59 +00008252 // If the type changed, it means we had an incomplete type that was
8253 // completed by the initializer. For example:
8254 // int ary[] = { 1, 3, 5 };
John McCall73076432012-01-05 00:13:19 +00008255 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman5c89c392012-02-23 02:25:10 +00008256 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith01888722011-12-15 19:20:59 +00008257 VDecl->setType(DclT);
Richard Smith01888722011-12-15 19:20:59 +00008258
Jordan Rosee10f4d32012-09-15 02:48:31 +00008259 if (!VDecl->isInvalidDecl()) {
Richard Smith01888722011-12-15 19:20:59 +00008260 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8261
Jordan Rosee10f4d32012-09-15 02:48:31 +00008262 if (VDecl->hasAttr<BlocksAttr>())
8263 checkRetainCycles(VDecl, Init);
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008264
8265 // It is safe to assign a weak reference into a strong variable.
8266 // Although this code can still have problems:
8267 // id x = self.weakProp;
8268 // id y = self.weakProp;
8269 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8270 // paths through the function. This should be revisited if
8271 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek904a3262012-12-20 22:31:27 +00008272 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rose58b6bdc2012-09-28 22:21:30 +00008273 DiagnosticsEngine::Level Level =
8274 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8275 Init->getLocStart());
8276 if (Level != DiagnosticsEngine::Ignored)
8277 getCurFunction()->markSafeWeakUse(Init);
8278 }
Jordan Rosee10f4d32012-09-15 02:48:31 +00008279 }
8280
Richard Smith41956372013-01-14 22:39:08 +00008281 // The initialization is usually a full-expression.
8282 //
8283 // FIXME: If this is a braced initialization of an aggregate, it is not
8284 // an expression, and each individual field initializer is a separate
8285 // full-expression. For instance, in:
8286 //
8287 // struct Temp { ~Temp(); };
8288 // struct S { S(Temp); };
8289 // struct T { S a, b; } t = { Temp(), Temp() }
8290 //
8291 // we should destroy the first Temp before constructing the second.
Fariborz Jahanianad48a502013-01-24 22:11:45 +00008292 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8293 false,
8294 VDecl->isConstexpr());
Richard Smith41956372013-01-14 22:39:08 +00008295 if (Result.isInvalid()) {
8296 VDecl->setInvalidDecl();
8297 return;
8298 }
8299 Init = Result.take();
8300
Richard Smith01888722011-12-15 19:20:59 +00008301 // Attach the initializer to the decl.
8302 VDecl->setInit(Init);
8303
8304 if (VDecl->isLocalVarDecl()) {
8305 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8306 // static storage duration shall be constant expressions or string literals.
8307 // C++ does not have this restriction.
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008308 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8309 if (VDecl->getStorageClass() == SC_Static)
8310 CheckForConstantInitializer(Init, DclT);
8311 // C89 is stricter than C99 for non-static aggregate types.
8312 // C89 6.5.7p3: All the expressions [...] in an initializer list
8313 // for an object that has aggregate or union type shall be
8314 // constant expressions.
8315 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanella82026302013-07-22 19:10:20 +00008316 isa<InitListExpr>(Init) &&
Enea Zaffanellab9a59352013-07-22 10:58:26 +00008317 !Init->isConstantInitializer(Context, false))
8318 Diag(Init->getExprLoc(),
8319 diag::ext_aggregate_init_not_constant)
8320 << Init->getSourceRange();
8321 }
Mike Stump1eb44332009-09-09 15:08:12 +00008322 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00008323 VDecl->getLexicalDeclContext()->isRecord()) {
8324 // This is an in-class initialization for a static data member, e.g.,
8325 //
8326 // struct S {
8327 // static const int value = 17;
8328 // };
8329
Douglas Gregor021c3b32009-03-11 23:00:04 +00008330 // C++ [class.mem]p4:
8331 // A member-declarator can contain a constant-initializer only
8332 // if it declares a static member (9.4) of const integral or
8333 // const enumeration type, see 9.4.2.
Richard Smithc6d990a2011-09-29 19:11:37 +00008334 //
Richard Smith01888722011-12-15 19:20:59 +00008335 // C++11 [class.static.data]p3:
Richard Smithc6d990a2011-09-29 19:11:37 +00008336 // If a non-volatile const static data member is of integral or
8337 // enumeration type, its declaration in the class definition can
8338 // specify a brace-or-equal-initializer in which every initalizer-clause
8339 // that is an assignment-expression is a constant expression. A static
8340 // data member of literal type can be declared in the class definition
8341 // with the constexpr specifier; if so, its declaration shall specify a
8342 // brace-or-equal-initializer in which every initializer-clause that is
8343 // an assignment-expression is a constant expression.
John McCall4e635642010-09-10 23:21:22 +00008344
8345 // Do nothing on dependent types.
Richard Smith01888722011-12-15 19:20:59 +00008346 if (DclT->isDependentType()) {
John McCall4e635642010-09-10 23:21:22 +00008347
Richard Smithc6d990a2011-09-29 19:11:37 +00008348 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith86c3ae42012-02-13 03:54:03 +00008349 // type. We separately check that every constexpr variable is of literal
8350 // type.
Richard Smithc6d990a2011-09-29 19:11:37 +00008351 } else if (VDecl->isConstexpr()) {
8352
John McCall4e635642010-09-10 23:21:22 +00008353 // Require constness.
Richard Smith01888722011-12-15 19:20:59 +00008354 } else if (!DclT.isConstQualified()) {
John McCall4e635642010-09-10 23:21:22 +00008355 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8356 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008357 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008358
8359 // We allow integer constant expressions in all cases.
Richard Smith01888722011-12-15 19:20:59 +00008360 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner24c38e12011-06-14 05:46:29 +00008361 // Check whether the expression is a constant expression.
8362 SourceLocation Loc;
Richard Smith80ad52f2013-01-02 11:42:31 +00008363 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith01888722011-12-15 19:20:59 +00008364 // In C++11, a non-constexpr const static data member with an
Richard Smith2da7a512011-09-29 21:28:14 +00008365 // in-class initializer cannot be volatile.
8366 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8367 else if (Init->isValueDependent())
Chris Lattner24c38e12011-06-14 05:46:29 +00008368 ; // Nothing to check.
8369 else if (Init->isIntegerConstantExpr(Context, &Loc))
8370 ; // Ok, it's an ICE!
8371 else if (Init->isEvaluatable(Context)) {
8372 // If we can constant fold the initializer through heroics, accept it,
8373 // but report this as a use of an extension for -pedantic.
8374 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8375 << Init->getSourceRange();
8376 } else {
8377 // Otherwise, this is some crazy unknown case. Report the issue at the
8378 // location provided by the isIntegerConstantExpr failed check.
8379 Diag(Loc, diag::err_in_class_initializer_non_constant)
8380 << Init->getSourceRange();
8381 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00008382 }
8383
Richard Smith01888722011-12-15 19:20:59 +00008384 // We allow foldable floating-point constants as an extension.
8385 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithb4b1d692013-01-25 04:22:16 +00008386 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8387 // it anyway and provide a fixit to add the 'constexpr'.
8388 if (getLangOpts().CPlusPlus11) {
David Blaikiea367e9d2013-01-29 22:26:08 +00008389 Diag(VDecl->getLocation(),
8390 diag::ext_in_class_initializer_float_type_cxx11)
8391 << DclT << Init->getSourceRange();
8392 Diag(VDecl->getLocStart(),
8393 diag::note_in_class_initializer_float_type_cxx11)
8394 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithb4b1d692013-01-25 04:22:16 +00008395 } else {
8396 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8397 << DclT << Init->getSourceRange();
John McCall4e635642010-09-10 23:21:22 +00008398
Richard Smithb4b1d692013-01-25 04:22:16 +00008399 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8400 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8401 << Init->getSourceRange();
8402 VDecl->setInvalidDecl();
8403 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00008404 }
Richard Smith947be192011-09-29 23:18:34 +00008405
Richard Smith01888722011-12-15 19:20:59 +00008406 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smitha10b9782013-04-22 15:31:51 +00008407 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith947be192011-09-29 23:18:34 +00008408 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith01888722011-12-15 19:20:59 +00008409 << DclT << Init->getSourceRange()
Richard Smith947be192011-09-29 23:18:34 +00008410 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8411 VDecl->setConstexpr(true);
8412
Richard Smithc6d990a2011-09-29 19:11:37 +00008413 } else {
8414 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith01888722011-12-15 19:20:59 +00008415 << DclT << Init->getSourceRange();
Richard Smithc6d990a2011-09-29 19:11:37 +00008416 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00008417 }
Steve Naroff248a7532008-04-15 22:42:06 +00008418 } else if (VDecl->isFileVarDecl()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008419 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008420 (!getLangOpts().CPlusPlus ||
Rafael Espindola5b34b9c2013-03-29 07:56:05 +00008421 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smithd0629eb2013-09-27 20:14:12 +00008422 VDecl->isExternC())) &&
8423 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff410e3e22007-09-12 20:13:48 +00008424 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00008425
Richard Smith01888722011-12-15 19:20:59 +00008426 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00008427 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlssonc5eb7312008-08-22 05:00:02 +00008428 CheckForConstantInitializer(Init, DclT);
Richard Smith6a570f62013-04-14 20:11:31 +00008429 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8430 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8431 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smithb6b127f2013-04-15 08:07:34 +00008432 !Init->isConstantInitializer(
8433 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6a570f62013-04-14 20:11:31 +00008434 // GNU C++98 edits for __thread, [basic.start.init]p4:
8435 // An object of thread storage duration shall not require dynamic
8436 // initialization.
8437 // FIXME: Need strict checking here.
8438 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8439 if (getLangOpts().CPlusPlus11)
8440 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8441 }
Steve Naroffbb204692007-09-12 14:07:44 +00008442 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008443
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008444 // We will represent direct-initialization similarly to copy-initialization:
8445 // int x(1); -as-> int x = 1;
8446 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8447 //
8448 // Clients that want to distinguish between the two forms, can check for
8449 // direct initializer using VarDecl::getInitStyle().
8450 // A major benefit is that clients that don't particularly care about which
8451 // exactly form was it (like the CodeGen) can handle both cases without
8452 // special case code.
8453
8454 // C++ 8.5p11:
8455 // The form of initialization (using parentheses or '=') is generally
8456 // insignificant, but does matter when the entity being initialized has a
8457 // class type.
8458 if (CXXDirectInit) {
8459 assert(DirectInit && "Call-style initializer must be direct init.");
8460 VDecl->setInitStyle(VarDecl::CallInit);
8461 } else if (DirectInit) {
8462 // This must be list-initialization. No other way is direct-initialization.
8463 VDecl->setInitStyle(VarDecl::ListInit);
8464 }
8465
John McCall2998d6b2011-01-19 11:48:09 +00008466 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00008467}
8468
John McCall7727acf2010-03-31 02:13:20 +00008469/// ActOnInitializerError - Given that there was an error parsing an
8470/// initializer for the given declaration, try to return to some form
8471/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00008472void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00008473 // Our main concern here is re-establishing invariants like "a
8474 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00008475 if (!D || D->isInvalidDecl()) return;
8476
8477 VarDecl *VD = dyn_cast<VarDecl>(D);
8478 if (!VD) return;
8479
Richard Smith34b41d92011-02-20 03:19:35 +00008480 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smith483b9f32011-02-21 20:05:19 +00008481 if (ParsingInitForAutoVars.count(D)) {
8482 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00008483 return;
8484 }
8485
John McCall7727acf2010-03-31 02:13:20 +00008486 QualType Ty = VD->getType();
8487 if (Ty->isDependentType()) return;
8488
8489 // Require a complete type.
8490 if (RequireCompleteType(VD->getLocation(),
8491 Context.getBaseElementType(Ty),
8492 diag::err_typecheck_decl_incomplete_type)) {
8493 VD->setInvalidDecl();
8494 return;
8495 }
8496
8497 // Require an abstract type.
8498 if (RequireNonAbstractType(VD->getLocation(), Ty,
8499 diag::err_abstract_type_in_decl,
8500 AbstractVariableType)) {
8501 VD->setInvalidDecl();
8502 return;
8503 }
8504
8505 // Don't bother complaining about constructors or destructors,
8506 // though.
8507}
8508
John McCalld226f652010-08-21 09:40:31 +00008509void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith34b41d92011-02-20 03:19:35 +00008510 bool TypeMayContainAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00008511 // If there is no declaration, there was an error parsing it. Just ignore it.
8512 if (RealDecl == 0)
8513 return;
8514
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008515 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8516 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00008517
Richard Smithdd4b3502011-12-25 21:17:58 +00008518 // C++11 [dcl.spec.auto]p3
Richard Smith34b41d92011-02-20 03:19:35 +00008519 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlsson6a75cd92009-07-11 00:34:39 +00008520 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8521 << Var->getDeclName() << Type;
8522 Var->setInvalidDecl();
8523 return;
8524 }
Mike Stump1eb44332009-09-09 15:08:12 +00008525
Richard Smithdd4b3502011-12-25 21:17:58 +00008526 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smithc6d990a2011-09-29 19:11:37 +00008527 // the constexpr specifier; if so, its declaration shall specify
8528 // a brace-or-equal-initializer.
Richard Smithdd4b3502011-12-25 21:17:58 +00008529 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8530 // the definition of a variable [...] or the declaration of a static data
8531 // member.
8532 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8533 if (Var->isStaticDataMember())
8534 Diag(Var->getLocation(),
8535 diag::err_constexpr_static_mem_var_requires_init)
8536 << Var->getDeclName();
8537 else
8538 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smithc6d990a2011-09-29 19:11:37 +00008539 Var->setInvalidDecl();
8540 return;
8541 }
8542
Douglas Gregor60c93c92010-02-09 07:26:29 +00008543 switch (Var->isThisDeclarationADefinition()) {
8544 case VarDecl::Definition:
8545 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8546 break;
8547
8548 // We have an out-of-line definition of a static data member
8549 // that has an in-class initializer, so we type-check this like
8550 // a declaration.
8551 //
8552 // Fall through
8553
8554 case VarDecl::DeclarationOnly:
8555 // It's only a declaration.
8556
8557 // Block scope. C99 6.7p7: If an identifier for an object is
8558 // declared with no linkage (C99 6.2.2p6), the type for the
8559 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00008560 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008561 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00008562 RequireCompleteType(Var->getLocation(), Type,
8563 diag::err_typecheck_decl_incomplete_type))
8564 Var->setInvalidDecl();
8565
8566 // Make sure that the type is not abstract.
8567 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8568 RequireNonAbstractType(Var->getLocation(), Type,
8569 diag::err_abstract_type_in_decl,
8570 AbstractVariableType))
8571 Var->setInvalidDecl();
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008572 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008573 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008574 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanian767a1a22012-08-17 21:44:55 +00008575 Diag(Var->getLocation(), diag::note_private_extern);
8576 }
Fariborz Jahanian4cc83c22012-08-15 18:42:26 +00008577
Douglas Gregor60c93c92010-02-09 07:26:29 +00008578 return;
8579
8580 case VarDecl::TentativeDefinition:
8581 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8582 // object that has file scope without an initializer, and without a
8583 // storage-class specifier or with the storage-class specifier "static",
8584 // constitutes a tentative definition. Note: A tentative definition with
8585 // external linkage is valid (C99 6.2.2p5).
8586 if (!Var->isInvalidDecl()) {
8587 if (const IncompleteArrayType *ArrayT
8588 = Context.getAsIncompleteArrayType(Type)) {
8589 if (RequireCompleteType(Var->getLocation(),
8590 ArrayT->getElementType(),
8591 diag::err_illegal_decl_array_incomplete_type))
8592 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00008593 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00008594 // C99 6.9.2p3: If the declaration of an identifier for an object is
8595 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8596 // declared type shall not be an incomplete type.
8597 // NOTE: code such as the following
8598 // static struct s;
8599 // struct s { int a; };
8600 // is accepted by gcc. Hence here we issue a warning instead of
8601 // an error and we do not invalidate the static declaration.
8602 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00008603 if (Var->isFirstDecl())
Douglas Gregor60c93c92010-02-09 07:26:29 +00008604 RequireCompleteType(Var->getLocation(), Type,
8605 diag::ext_typecheck_decl_incomplete_type);
8606 }
8607 }
8608
8609 // Record the tentative definition; we're done.
8610 if (!Var->isInvalidDecl())
8611 TentativeDefinitions.push_back(Var);
8612 return;
8613 }
8614
8615 // Provide a specific diagnostic for uninitialized variable
8616 // definitions with incomplete array type.
8617 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00008618 Diag(Var->getLocation(),
8619 diag::err_typecheck_incomplete_array_needs_initializer);
8620 Var->setInvalidDecl();
8621 return;
8622 }
8623
John McCallb567a8b2010-08-01 01:25:24 +00008624 // Provide a specific diagnostic for uninitialized variable
8625 // definitions with reference type.
8626 if (Type->isReferenceType()) {
8627 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8628 << Var->getDeclName()
8629 << SourceRange(Var->getLocation(), Var->getLocation());
8630 Var->setInvalidDecl();
8631 return;
8632 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008633
8634 // Do not attempt to type-check the default initializer for a
8635 // variable with dependent type.
8636 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00008637 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00008638
Douglas Gregor60c93c92010-02-09 07:26:29 +00008639 if (Var->isInvalidDecl())
8640 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00008641
Douglas Gregor60c93c92010-02-09 07:26:29 +00008642 if (RequireCompleteType(Var->getLocation(),
8643 Context.getBaseElementType(Type),
8644 diag::err_typecheck_decl_incomplete_type)) {
8645 Var->setInvalidDecl();
8646 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008647 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008648
Douglas Gregor60c93c92010-02-09 07:26:29 +00008649 // The variable can not have an abstract class type.
8650 if (RequireNonAbstractType(Var->getLocation(), Type,
8651 diag::err_abstract_type_in_decl,
8652 AbstractVariableType)) {
8653 Var->setInvalidDecl();
8654 return;
8655 }
8656
Douglas Gregor4337dc72011-05-21 17:52:48 +00008657 // Check for jumps past the implicit initializer. C++0x
8658 // clarifies that this applies to a "variable with automatic
8659 // storage duration", not a "local variable".
Richard Smith0e9e9812011-10-20 21:42:12 +00008660 // C++11 [stmt.dcl]p3
Douglas Gregor4337dc72011-05-21 17:52:48 +00008661 // A program that jumps from a point where a variable with automatic
8662 // storage duration is not in scope to a point where it is in scope is
8663 // ill-formed unless the variable has scalar type, class type with a
8664 // trivial default constructor and a trivial destructor, a cv-qualified
8665 // version of one of these types, or an array of one of the preceding
8666 // types and is declared without an initializer.
David Blaikie4e4d0842012-03-11 07:00:24 +00008667 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008668 if (const RecordType *Record
8669 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Sean Hunta6bff2c2011-05-11 22:50:12 +00008670 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smith0e9e9812011-10-20 21:42:12 +00008671 // Mark the function for further checking even if the looser rules of
8672 // C++11 do not require such checks, so that we can diagnose
8673 // incompatibilities with C++98.
8674 if (!CXXRecord->isPOD())
Sean Hunta6bff2c2011-05-11 22:50:12 +00008675 getCurFunction()->setHasBranchProtectedScope();
8676 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00008677 }
Douglas Gregor4337dc72011-05-21 17:52:48 +00008678
8679 // C++03 [dcl.init]p9:
8680 // If no initializer is specified for an object, and the
8681 // object is of (possibly cv-qualified) non-POD class type (or
8682 // array thereof), the object shall be default-initialized; if
8683 // the object is of const-qualified type, the underlying class
8684 // type shall have a user-declared default
8685 // constructor. Otherwise, if no initializer is specified for
8686 // a non- static object, the object and its subobjects, if
8687 // any, have an indeterminate initial value); if the object
8688 // or any of its subobjects are of const-qualified type, the
8689 // program is ill-formed.
8690 // C++0x [dcl.init]p11:
8691 // If no initializer is specified for an object, the object is
8692 // default-initialized; [...].
8693 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8694 InitializationKind Kind
8695 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00008696
8697 InitializationSequence InitSeq(*this, Entity, Kind, None);
8698 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor4337dc72011-05-21 17:52:48 +00008699 if (Init.isInvalid())
8700 Var->setInvalidDecl();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008701 else if (Init.get()) {
Douglas Gregor4337dc72011-05-21 17:52:48 +00008702 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00008703 // This is important for template substitution.
8704 Var->setInitStyle(VarDecl::CallInit);
8705 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00008706
John McCall2998d6b2011-01-19 11:48:09 +00008707 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008708 }
8709}
8710
Richard Smithad762fc2011-04-14 22:09:26 +00008711void Sema::ActOnCXXForRangeDecl(Decl *D) {
8712 VarDecl *VD = dyn_cast<VarDecl>(D);
8713 if (!VD) {
8714 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8715 D->setInvalidDecl();
8716 return;
8717 }
8718
8719 VD->setCXXForRangeDecl(true);
8720
8721 // for-range-declaration cannot be given a storage class specifier.
8722 int Error = -1;
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008723 switch (VD->getStorageClass()) {
Richard Smithad762fc2011-04-14 22:09:26 +00008724 case SC_None:
8725 break;
8726 case SC_Extern:
8727 Error = 0;
8728 break;
8729 case SC_Static:
8730 Error = 1;
8731 break;
8732 case SC_PrivateExtern:
8733 Error = 2;
8734 break;
8735 case SC_Auto:
8736 Error = 3;
8737 break;
8738 case SC_Register:
8739 Error = 4;
8740 break;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00008741 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne8be0c742011-09-20 12:40:26 +00008742 llvm_unreachable("Unexpected storage class");
Richard Smithad762fc2011-04-14 22:09:26 +00008743 }
Richard Smithc6d990a2011-09-29 19:11:37 +00008744 if (VD->isConstexpr())
8745 Error = 5;
Richard Smithad762fc2011-04-14 22:09:26 +00008746 if (Error != -1) {
8747 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8748 << VD->getDeclName() << Error;
8749 D->setInvalidDecl();
8750 }
8751}
8752
John McCall2998d6b2011-01-19 11:48:09 +00008753void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8754 if (var->isInvalidDecl()) return;
8755
John McCallf85e1932011-06-15 23:02:42 +00008756 // In ARC, don't allow jumps past the implicit initialization of a
8757 // local retaining variable.
David Blaikie4e4d0842012-03-11 07:00:24 +00008758 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00008759 var->hasLocalStorage()) {
8760 switch (var->getType().getObjCLifetime()) {
8761 case Qualifiers::OCL_None:
8762 case Qualifiers::OCL_ExplicitNone:
8763 case Qualifiers::OCL_Autoreleasing:
8764 break;
8765
8766 case Qualifiers::OCL_Weak:
8767 case Qualifiers::OCL_Strong:
8768 getCurFunction()->setHasBranchProtectedScope();
8769 break;
8770 }
8771 }
8772
Eli Friedmane4851f22012-10-23 20:19:32 +00008773 if (var->isThisDeclarationADefinition() &&
Eli Friedman2ae28e52013-09-24 23:10:08 +00008774 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimekacaf1102012-12-12 13:26:54 +00008775 getDiagnostics().getDiagnosticLevel(
8776 diag::warn_missing_variable_declarations,
8777 var->getLocation())) {
Eli Friedmane4851f22012-10-23 20:19:32 +00008778 // Find a previous declaration that's not a definition.
8779 VarDecl *prev = var->getPreviousDecl();
8780 while (prev && prev->isThisDeclarationADefinition())
8781 prev = prev->getPreviousDecl();
8782
8783 if (!prev)
8784 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8785 }
8786
Richard Smith6a570f62013-04-14 20:11:31 +00008787 if (var->getTLSKind() == VarDecl::TLS_Static &&
8788 var->getType().isDestructedType()) {
8789 // GNU C++98 edits for __thread, [basic.start.term]p3:
8790 // The type of an object with thread storage duration shall not
8791 // have a non-trivial destructor.
8792 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8793 if (getLangOpts().CPlusPlus11)
8794 Diag(var->getLocation(), diag::note_use_thread_local);
8795 }
8796
John McCall2998d6b2011-01-19 11:48:09 +00008797 // All the following checks are C++ only.
David Blaikie4e4d0842012-03-11 07:00:24 +00008798 if (!getLangOpts().CPlusPlus) return;
John McCall2998d6b2011-01-19 11:48:09 +00008799
Richard Smitha67d5032012-11-09 23:03:14 +00008800 QualType type = var->getType();
8801 if (type->isDependentType()) return;
John McCall2998d6b2011-01-19 11:48:09 +00008802
8803 // __block variables might require us to capture a copy-initializer.
8804 if (var->hasAttr<BlocksAttr>()) {
8805 // It's currently invalid to ever have a __block variable with an
8806 // array type; should we diagnose that here?
8807
8808 // Regardless, we don't want to ignore array nesting when
8809 // constructing this copy.
John McCall2998d6b2011-01-19 11:48:09 +00008810 if (type->isStructureOrClassType()) {
John McCallb760f112013-03-22 02:10:40 +00008811 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall2998d6b2011-01-19 11:48:09 +00008812 SourceLocation poi = var->getLocation();
John McCallf4b88a42012-03-10 09:33:50 +00008813 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregor6cda3e62013-03-07 22:38:24 +00008814 ExprResult result
8815 = PerformMoveOrCopyInitialization(
8816 InitializedEntity::InitializeBlock(poi, type, false),
8817 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall2998d6b2011-01-19 11:48:09 +00008818 if (!result.isInvalid()) {
8819 result = MaybeCreateExprWithCleanups(result);
8820 Expr *init = result.takeAs<Expr>();
8821 Context.setBlockVarCopyInits(var, init);
8822 }
8823 }
8824 }
8825
Richard Smith66f85712011-11-07 22:16:17 +00008826 Expr *Init = var->getInit();
8827 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smitha67d5032012-11-09 23:03:14 +00008828 QualType baseType = Context.getBaseElementType(type);
Richard Smith66f85712011-11-07 22:16:17 +00008829
Richard Smith9568f0c2012-10-29 18:26:47 +00008830 if (!var->getDeclContext()->isDependentContext() &&
8831 Init && !Init->isValueDependent()) {
Richard Smith099e7f62011-12-19 06:19:21 +00008832 if (IsGlobal && !var->isConstexpr() &&
8833 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8834 var->getLocation())
Eli Friedman21cde052013-07-16 22:40:53 +00008835 != DiagnosticsEngine::Ignored) {
8836 // Warn about globals which don't have a constant initializer. Don't
8837 // warn about globals with a non-trivial destructor because we already
8838 // warned about them.
8839 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8840 if (!(RD && !RD->hasTrivialDestructor()) &&
8841 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8842 Diag(var->getLocation(), diag::warn_global_constructor)
8843 << Init->getSourceRange();
8844 }
Richard Smith099e7f62011-12-19 06:19:21 +00008845
Richard Smith099e7f62011-12-19 06:19:21 +00008846 if (var->isConstexpr()) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008847 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00008848 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8849 SourceLocation DiagLoc = var->getLocation();
8850 // If the note doesn't add any useful information other than a source
8851 // location, fold it into the primary diagnostic.
8852 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8853 diag::note_invalid_subexpr_in_const_expr) {
8854 DiagLoc = Notes[0].first;
8855 Notes.clear();
8856 }
8857 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8858 << var << Init->getSourceRange();
8859 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8860 Diag(Notes[I].first, Notes[I].second);
8861 }
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00008862 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smith099e7f62011-12-19 06:19:21 +00008863 // Check whether the initializer of a const variable of integral or
8864 // enumeration type is an ICE now, since we can't tell whether it was
8865 // initialized by a constant expression if we check later.
8866 var->checkInitIsICE();
8867 }
Richard Smith66f85712011-11-07 22:16:17 +00008868 }
John McCall2998d6b2011-01-19 11:48:09 +00008869
8870 // Require the destructor.
8871 if (const RecordType *recordType = baseType->getAs<RecordType>())
8872 FinalizeVarWithDestructor(var, recordType);
8873}
8874
Richard Smith483b9f32011-02-21 20:05:19 +00008875/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8876/// any semantic actions necessary after any initializer has been attached.
8877void
8878Sema::FinalizeDeclaration(Decl *ThisDecl) {
8879 // Note that we are no longer parsing the initializer for this declaration.
8880 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008881
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008882 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindolada844b32013-01-03 04:05:19 +00008883 if (!VD)
8884 return;
8885
Rafael Espindola29535ba2013-08-16 23:18:50 +00008886 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8887 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8888 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8889 VD->dropAttr<UsedAttr>();
8890 }
8891 }
8892
Rafael Espindolab1c0e202013-10-22 21:39:03 +00008893 if (!VD->isInvalidDecl() &&
8894 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8895 if (const VarDecl *Def = VD->getDefinition()) {
8896 if (Def->hasAttr<AliasAttr>()) {
8897 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8898 << VD->getDeclName();
8899 Diag(Def->getLocation(), diag::note_previous_definition);
8900 VD->setInvalidDecl();
8901 }
8902 }
8903 }
8904
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008905 const DeclContext *DC = VD->getDeclContext();
8906 // If there's a #pragma GCC visibility in scope, and this isn't a class
8907 // member, set the visibility of this variable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00008908 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindola4c8cba82013-02-22 17:59:16 +00008909 AddPushedVisibilityAttribute(VD);
8910
Rafael Espindola6769ccb2013-01-03 04:29:20 +00008911 if (VD->isFileVarDecl())
8912 MarkUnusedFileScopedDecl(VD);
8913
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008914 // Now we have parsed the initializer and can update the table of magic
8915 // tag values.
Rafael Espindolada844b32013-01-03 04:05:19 +00008916 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8917 !VD->getType()->isIntegralOrEnumerationType())
8918 return;
8919
8920 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8921 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8922 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8923 I != E; ++I) {
8924 const Expr *MagicValueExpr = VD->getInit();
8925 if (!MagicValueExpr) {
8926 continue;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008927 }
Rafael Espindolada844b32013-01-03 04:05:19 +00008928 llvm::APSInt MagicValueInt;
8929 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8930 Diag(I->getRange().getBegin(),
8931 diag::err_type_tag_for_datatype_not_ice)
8932 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8933 continue;
8934 }
8935 if (MagicValueInt.getActiveBits() > 64) {
8936 Diag(I->getRange().getBegin(),
8937 diag::err_type_tag_for_datatype_too_large)
8938 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8939 continue;
8940 }
8941 uint64_t MagicValue = MagicValueInt.getZExtValue();
8942 RegisterTypeTagForDatatype(I->getArgumentKind(),
8943 MagicValue,
8944 I->getMatchingCType(),
8945 I->getLayoutCompatible(),
8946 I->getMustBeNull());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008947 }
Richard Smith483b9f32011-02-21 20:05:19 +00008948}
8949
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008950Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8951 ArrayRef<Decl *> Group) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00008952 SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008953
8954 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00008955 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00008956
David Majnemeraa824612013-09-17 23:57:10 +00008957 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008958 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemeraa824612013-09-17 23:57:10 +00008959 if (Decl *D = Group[i]) {
8960 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8961 if (!FirstDeclaratorInGroup)
8962 FirstDeclaratorInGroup = DD;
Richard Smith406c38e2011-02-23 00:37:57 +00008963 Decls.push_back(D);
David Majnemeraa824612013-09-17 23:57:10 +00008964 }
Richard Smith406c38e2011-02-23 00:37:57 +00008965
Eli Friedman5e867c82013-07-10 00:30:46 +00008966 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemeraa824612013-09-17 23:57:10 +00008967 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman5e867c82013-07-10 00:30:46 +00008968 HandleTagNumbering(*this, Tag);
David Majnemeraa824612013-09-17 23:57:10 +00008969 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8970 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8971 }
Eli Friedman5e867c82013-07-10 00:30:46 +00008972 }
David Blaikie66cff722012-11-14 01:52:05 +00008973
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008974 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith406c38e2011-02-23 00:37:57 +00008975}
8976
8977/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8978/// group, performing any necessary semantic checking.
8979Sema::DeclGroupPtrTy
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008980Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith406c38e2011-02-23 00:37:57 +00008981 bool TypeMayContainAuto) {
Richard Smith34b41d92011-02-20 03:19:35 +00008982 // C++0x [dcl.spec.auto]p7:
8983 // If the type deduced for the template parameter U is not the same in each
8984 // deduction, the program is ill-formed.
8985 // FIXME: When initializer-list support is added, a distinction is needed
8986 // between the deduced type U and the deduced type which 'auto' stands for.
8987 // auto a = 0, b = { 1, 2, 3 };
8988 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008989 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith34b41d92011-02-20 03:19:35 +00008990 QualType Deduced;
8991 CanQualType DeducedCanon;
8992 VarDecl *DeducedDecl = 0;
Rafael Espindola4549d7f2013-07-09 12:05:01 +00008993 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith34b41d92011-02-20 03:19:35 +00008994 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8995 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith406c38e2011-02-23 00:37:57 +00008996 // Don't reissue diagnostics when instantiating a template.
8997 if (AT && D->isInvalidDecl())
8998 break;
Richard Smithdc7a4f52013-04-30 13:56:41 +00008999 QualType U = AT ? AT->getDeducedType() : QualType();
9000 if (!U.isNull()) {
Richard Smith34b41d92011-02-20 03:19:35 +00009001 CanQualType UCanon = Context.getCanonicalType(U);
9002 if (Deduced.isNull()) {
9003 Deduced = U;
9004 DeducedCanon = UCanon;
9005 DeducedDecl = D;
9006 } else if (DeducedCanon != UCanon) {
Richard Smith406c38e2011-02-23 00:37:57 +00009007 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9008 diag::err_auto_different_deductions)
Richard Smithffd015e2013-05-04 04:19:27 +00009009 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith34b41d92011-02-20 03:19:35 +00009010 << Deduced << DeducedDecl->getDeclName()
9011 << U << D->getDeclName()
9012 << DeducedDecl->getInit()->getSourceRange()
9013 << D->getInit()->getSourceRange();
Richard Smith406c38e2011-02-23 00:37:57 +00009014 D->setInvalidDecl();
Richard Smith34b41d92011-02-20 03:19:35 +00009015 break;
9016 }
9017 }
9018 }
9019 }
9020 }
9021
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009022 ActOnDocumentableDecls(Group);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009023
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009024 return DeclGroupPtrTy::make(
9025 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00009026}
Steve Naroffe1223f72007-08-28 03:03:08 +00009027
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009028void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009029 ActOnDocumentableDecls(D);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009030}
9031
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009032void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009033 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009034 if (Group.empty() || !Group[0])
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009035 return;
9036
9037 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9038 Group[0]->getLocation())
9039 == DiagnosticsEngine::Ignored)
9040 return;
9041
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009042 if (Group.size() >= 2) {
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009043 // This is a decl group. Normally it will contain only declarations
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009044 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009045 // additional declaration references:
9046 // 'typedef struct S {} S;'
9047 // 'typedef struct S *S;'
9048 // 'struct S *pS;'
9049 // FinalizeDeclaratorGroup adds these as separate declarations.
9050 Decl *MaybeTagDecl = Group[0];
9051 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009052 Group = Group.slice(1);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009053 }
9054 }
9055
9056 // See if there are any new comments that are not attached to a decl.
9057 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9058 if (!Comments.empty() &&
9059 !Comments.back()->isAttached()) {
9060 // There is at least one comment that not attached to a decl.
9061 // Maybe it should be attached to one of these decls?
9062 //
9063 // Note that this way we pick up not only comments that precede the
9064 // declaration, but also comments that *follow* the declaration -- thanks to
9065 // the lookahead in the lexer: we've consumed the semicolon and looked
9066 // ahead through comments.
Rafael Espindola4549d7f2013-07-09 12:05:01 +00009067 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko19523542012-09-29 11:40:46 +00009068 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00009069 }
9070}
Chris Lattner682bf922009-03-29 16:50:03 +00009071
Chris Lattner04421082008-04-08 04:40:51 +00009072/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9073/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00009074Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00009075 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00009076
Chris Lattner04421082008-04-08 04:40:51 +00009077 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Valifad9e132013-09-26 19:54:12 +00009078
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009079 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCalld931b082010-08-26 03:08:43 +00009080 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009081 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00009082 StorageClass = SC_Register;
David Blaikie4e4d0842012-03-11 07:00:24 +00009083 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne7a8a2e32011-10-21 11:55:09 +00009084 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9085 StorageClass = SC_Auto;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00009086 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00009087 Diag(DS.getStorageClassSpecLoc(),
9088 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00009089 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00009090 }
Eli Friedman63054b32009-04-19 20:27:55 +00009091
Richard Smithec642442013-04-12 22:46:28 +00009092 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9093 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9094 << DeclSpec::getSpecifierName(TSCS);
9095 if (DS.isConstexprSpecified())
9096 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smithaf1fc7a2011-08-15 21:04:07 +00009097 << 0;
Eli Friedman63054b32009-04-19 20:27:55 +00009098
Richard Smithec642442013-04-12 22:46:28 +00009099 DiagnoseFunctionSpecifiers(DS);
Eli Friedman85a53192009-04-07 19:37:57 +00009100
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00009101 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00009102 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00009103
David Blaikie4e4d0842012-03-11 07:00:24 +00009104 if (getLangOpts().CPlusPlus) {
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009105 // Check that there are no default arguments inside the type of this
9106 // parameter.
9107 CheckExtraCXXDefaultArguments(D);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00009108
9109 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9110 if (D.getCXXScopeSpec().isSet()) {
9111 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9112 << D.getCXXScopeSpec().getRange();
9113 D.getCXXScopeSpec().clear();
9114 }
Douglas Gregor402abb52009-05-28 23:31:59 +00009115 }
9116
Sean Hunt7533a5b2010-11-03 01:07:06 +00009117 // Ensure we have a valid name
9118 IdentifierInfo *II = 0;
9119 if (D.hasName()) {
9120 II = D.getIdentifier();
9121 if (!II) {
9122 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9123 << GetNameForDeclarator(D).getName().getAsString();
9124 D.setInvalidType(true);
9125 }
9126 }
9127
Chris Lattnerd84aac12010-02-22 00:40:25 +00009128 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00009129 if (II) {
John McCall10f28732010-03-18 06:42:38 +00009130 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9131 ForRedeclaration);
9132 LookupName(R, S);
9133 if (R.isSingleResult()) {
9134 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00009135 if (PrevDecl->isTemplateParameter()) {
9136 // Maybe we will complain about the shadowed template parameter.
9137 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9138 // Just pretend that we didn't see the previous declaration.
9139 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00009140 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00009141 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00009142 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00009143
Chris Lattnercf79b012009-01-21 02:38:50 +00009144 // Recover by removing the name
9145 II = 0;
9146 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009147 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00009148 }
Chris Lattner04421082008-04-08 04:40:51 +00009149 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009150 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00009151
John McCall7a9813c2010-01-22 00:28:27 +00009152 // Temporarily put parameter variables in the translation unit, not
9153 // the enclosing context. This prevents them from accidentally
9154 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009155 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00009156 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009157 D.getIdentifierLoc(), II,
9158 parmDeclType, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009159 StorageClass);
Mike Stump1eb44332009-09-09 15:08:12 +00009160
Chris Lattnereaaebc72009-04-25 08:06:05 +00009161 if (D.isInvalidType())
John McCallfb44de92011-05-01 22:35:37 +00009162 New->setInvalidDecl();
9163
9164 assert(S->isFunctionPrototypeScope());
9165 assert(S->getFunctionPrototypeDepth() >= 1);
9166 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9167 S->getNextFunctionPrototypeIndex());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009168
Douglas Gregor44b43212008-12-11 16:49:14 +00009169 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00009170 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009171 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00009172 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00009173
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009174 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00009175
Douglas Gregore3895852011-09-12 18:37:38 +00009176 if (D.getDeclSpec().isModulePrivateSpecified())
9177 Diag(New->getLocation(), diag::err_module_private_local)
9178 << 1 << New->getDeclName()
9179 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9180 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9181
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00009182 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00009183 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9184 }
John McCalld226f652010-08-21 09:40:31 +00009185 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00009186}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00009187
John McCall82dc0092010-06-04 11:21:44 +00009188/// \brief Synthesizes a variable for a parameter arising from a
9189/// typedef.
9190ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9191 SourceLocation Loc,
9192 QualType T) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009193 /* FIXME: setting StartLoc == Loc.
9194 Would it be worth to modify callers so as to provide proper source
9195 location for the unnamed parameters, embedding the parameter's type? */
9196 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCall82dc0092010-06-04 11:21:44 +00009197 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009198 SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00009199 Param->setImplicit();
9200 return Param;
9201}
9202
John McCallfbce0e12010-08-24 09:05:15 +00009203void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9204 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00009205 // Don't diagnose unused-parameter errors in template instantiations; we
9206 // will already have done so in the template itself.
9207 if (!ActiveTemplateInstantiations.empty())
9208 return;
9209
9210 for (; Param != ParamEnd; ++Param) {
Eli Friedmandd9d6452012-01-13 23:41:25 +00009211 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallfbce0e12010-08-24 09:05:15 +00009212 !(*Param)->hasAttr<UnusedAttr>()) {
9213 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9214 << (*Param)->getDeclName();
9215 }
9216 }
9217}
9218
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009219void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9220 ParmVarDecl * const *ParamEnd,
9221 QualType ReturnTy,
9222 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009223 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009224 return;
9225
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009226 // Warn if the return value is pass-by-value and larger than the specified
9227 // threshold.
Eli Friedmand18840d2012-01-09 23:46:59 +00009228 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009229 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009230 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009231 Diag(D->getLocation(), diag::warn_return_value_size)
9232 << D->getDeclName() << Size;
9233 }
9234
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009235 // Warn if any parameter is pass-by-value and larger than the specified
9236 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009237 for (; Param != ParamEnd; ++Param) {
9238 QualType T = (*Param)->getType();
Eli Friedmand18840d2012-01-09 23:46:59 +00009239 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009240 continue;
9241 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00009242 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009243 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9244 << (*Param)->getDeclName() << Size;
9245 }
9246}
9247
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009248ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9249 SourceLocation NameLoc, IdentifierInfo *Name,
9250 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009251 VarDecl::StorageClass StorageClass) {
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009252 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikie4e4d0842012-03-11 07:00:24 +00009253 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00009254 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009255 T->isObjCLifetimeType()) {
9256
9257 Qualifiers::ObjCLifetime lifetime;
9258
9259 // Special cases for arrays:
9260 // - if it's const, use __unsafe_unretained
9261 // - otherwise, it's an error
9262 if (T->isArrayType()) {
9263 if (!T.isConstQualified()) {
9264 DelayedDiagnostics.add(
9265 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanian175fb102011-10-03 22:11:57 +00009266 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Klecknerc910d4c2013-06-08 18:19:52 +00009267 }
9268 lifetime = Qualifiers::OCL_ExplicitNone;
9269 } else {
9270 lifetime = T->getObjCARCImplicitLifetime();
9271 }
9272 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCallf85e1932011-06-15 23:02:42 +00009273 }
9274
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009275 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor79e6bd32011-07-12 04:42:08 +00009276 Context.getAdjustedParameterType(T),
9277 TSInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009278 StorageClass, 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009279
9280 // Parameters can not be abstract class types.
9281 // For record types, this is done by the AbstractClassUsageDiagnoser once
9282 // the class has been completely parsed.
9283 if (!CurContext->isRecord() &&
9284 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9285 AbstractParamType))
9286 New->setInvalidDecl();
9287
9288 // Parameter declarators cannot be interface types. All ObjC objects are
9289 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00009290 if (T->isObjCObjectType()) {
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009291 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009292 Diag(NameLoc,
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009293 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00009294 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +00009295 T = Context.getObjCObjectPointerType(T);
9296 New->setType(T);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00009297 }
9298
9299 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9300 // duration shall not be qualified by an address-space qualifier."
9301 // Since all parameters have automatic store duration, they can not have
9302 // an address space.
9303 if (T.getAddressSpace() != 0) {
9304 Diag(NameLoc, diag::err_arg_with_address_space);
9305 New->setInvalidDecl();
9306 }
9307
9308 return New;
9309}
9310
Douglas Gregora3a83512009-04-01 23:51:29 +00009311void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9312 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009313 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00009314
Reid Spencer5f016e22007-07-11 17:01:13 +00009315 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9316 // for a K&R function.
9317 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00009318 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9319 --i;
Chris Lattner04421082008-04-08 04:40:51 +00009320 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009321 SmallString<256> Code;
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009322 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009323 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00009324 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00009325 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00009326 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00009327 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00009328
Reid Spencer5f016e22007-07-11 17:01:13 +00009329 // Implicitly declare the argument as type 'int' for lack of a better
9330 // type.
John McCall0b7e6782011-03-24 11:26:52 +00009331 AttributeFactory attrs;
9332 DeclSpec DS(attrs);
Chris Lattner04421082008-04-08 04:40:51 +00009333 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00009334 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00009335 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00009336 PrevSpec, DiagID);
Abramo Bagnara16467f22012-10-04 21:38:29 +00009337 // Use the identifier location for the type source range.
9338 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9339 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattner04421082008-04-08 04:40:51 +00009340 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9341 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00009342 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00009343 }
9344 }
Mike Stump1eb44332009-09-09 15:08:12 +00009345 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00009346}
9347
Richard Smith87162c22012-04-17 22:30:01 +00009348Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00009349 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00009350 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00009351 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00009352
Douglas Gregor45fa5602011-11-07 20:56:01 +00009353 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009354 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner682bf922009-03-29 16:50:03 +00009355 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00009356}
9357
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009358static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9359 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009360 // Don't warn about invalid declarations.
9361 if (FD->isInvalidDecl())
9362 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009363
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009364 // Or declarations that aren't global.
9365 if (!FD->isGlobal())
9366 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009367
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009368 // Don't warn about C++ member functions.
9369 if (isa<CXXMethodDecl>(FD))
9370 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009371
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009372 // Don't warn about 'main'.
9373 if (FD->isMain())
9374 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009375
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009376 // Don't warn about inline functions.
John McCall850d3b32011-03-22 07:16:37 +00009377 if (FD->isInlined())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009378 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00009379
9380 // Don't warn about function templates.
9381 if (FD->getDescribedFunctionTemplate())
9382 return false;
9383
9384 // Don't warn about function template specializations.
9385 if (FD->isFunctionTemplateSpecialization())
9386 return false;
9387
Tanya Lattnera95b4f72012-07-26 00:08:28 +00009388 // Don't warn for OpenCL kernels.
9389 if (FD->hasAttr<OpenCLKernelAttr>())
9390 return false;
Richard Smitha41c97a2013-09-20 01:15:31 +00009391
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009392 bool MissingPrototype = true;
Douglas Gregoref96ee02012-01-14 16:38:05 +00009393 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9394 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009395 // Ignore any declarations that occur in function or method
9396 // scope, because they aren't visible from the header.
Richard Smitha41c97a2013-09-20 01:15:31 +00009397 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009398 continue;
Richard Smitha41c97a2013-09-20 01:15:31 +00009399
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009400 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009401 if (FD->getNumParams() == 0)
9402 PossibleZeroParamPrototype = Prev;
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009403 break;
9404 }
Richard Smitha41c97a2013-09-20 01:15:31 +00009405
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009406 return MissingPrototype;
9407}
9408
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009409void
9410Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9411 const FunctionDecl *EffectiveDefinition) {
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009412 // Don't complain if we're in GNU89 mode and the previous definition
9413 // was an extern inline function.
Rafael Espindolab1c0e202013-10-22 21:39:03 +00009414 const FunctionDecl *Definition = EffectiveDefinition;
9415 if (!Definition)
9416 if (!FD->isDefined(Definition))
9417 return;
9418
9419 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009420 return;
9421
9422 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9423 Definition->getStorageClass() == SC_Extern)
9424 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikie4e4d0842012-03-11 07:00:24 +00009425 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindolaa2770ab2013-10-22 15:18:22 +00009426 else
9427 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9428
9429 Diag(Definition->getLocation(), diag::note_previous_definition);
9430 FD->setInvalidDecl();
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009431}
Faisal Valic00e4192013-11-07 05:17:06 +00009432
9433
Faisal Valibef582b2013-10-23 16:10:50 +00009434static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9435 Sema &S) {
9436 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Valid78d6592013-11-12 01:40:44 +00009437
9438 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valibef582b2013-10-23 16:10:50 +00009439 LSI->CallOperator = CallOperator;
9440 LSI->Lambda = LambdaClass;
9441 LSI->ReturnType = CallOperator->getResultType();
9442 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9443
9444 if (LCD == LCD_None)
9445 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9446 else if (LCD == LCD_ByCopy)
9447 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9448 else if (LCD == LCD_ByRef)
9449 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9450 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9451
9452 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9453 LSI->Mutable = !CallOperator->isConst();
9454
Faisal Valic00e4192013-11-07 05:17:06 +00009455 // Add the captures to the LSI so they can be noted as already
9456 // captured within tryCaptureVar.
9457 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9458 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9459 if (C->capturesVariable()) {
9460 VarDecl *VD = C->getCapturedVar();
9461 if (VD->isInitCapture())
9462 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9463 QualType CaptureType = VD->getType();
9464 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9465 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9466 /*RefersToEnclosingLocal*/true, C->getLocation(),
9467 /*EllipsisLoc*/C->isPackExpansion()
9468 ? C->getEllipsisLoc() : SourceLocation(),
9469 CaptureType, /*Expr*/ 0);
9470
9471 } else if (C->capturesThis()) {
9472 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9473 S.getCurrentThisType(), /*Expr*/ 0);
9474 }
9475 }
Faisal Valibef582b2013-10-23 16:10:50 +00009476}
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009477
John McCalld226f652010-08-21 09:40:31 +00009478Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00009479 // Clear the last template instantiation error context.
9480 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9481
Douglas Gregor52591bf2009-06-24 00:54:41 +00009482 if (!D)
9483 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00009484 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00009485
John McCalld226f652010-08-21 09:40:31 +00009486 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00009487 FD = FunTmpl->getTemplatedDecl();
9488 else
John McCalld226f652010-08-21 09:40:31 +00009489 FD = cast<FunctionDecl>(D);
Faisal Valifad9e132013-09-26 19:54:12 +00009490 // If we are instantiating a generic lambda call operator, push
9491 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valibef582b2013-10-23 16:10:50 +00009492 // that's already been calculated (ActOnLambdaExpr) to prime the current
9493 // LambdaScopeInfo.
9494 // When the template operator is being specialized, the LambdaScopeInfo,
9495 // has to be properly restored so that tryCaptureVariable doesn't try
9496 // and capture any new variables. In addition when calculating potential
9497 // captures during transformation of nested lambdas, it is necessary to
9498 // have the LSI properly restored.
Faisal Vali998c5182013-09-29 20:15:45 +00009499 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Valifad9e132013-09-26 19:54:12 +00009500 assert(ActiveTemplateInstantiations.size() &&
9501 "There should be an active template instantiation on the stack "
9502 "when instantiating a generic lambda!");
Faisal Valibef582b2013-10-23 16:10:50 +00009503 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Valifad9e132013-09-26 19:54:12 +00009504 }
9505 else
9506 // Enter a new function scope
9507 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00009508
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009509 // See if this is a redefinition.
Francois Pichetd4a0caf2011-04-22 23:20:44 +00009510 if (!FD->isLateTemplateParsed())
9511 CheckForFunctionRedefinition(FD);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00009512
Douglas Gregorcda9c672009-02-16 17:45:42 +00009513 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009514 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindolaad24ad42013-06-13 18:34:17 +00009515 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9516 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00009517 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00009518 FD->setInvalidDecl();
9519 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00009520 }
9521
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009522 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00009523 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9524 QualType ResultType = FD->getResultType();
9525 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00009526 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00009527 RequireCompleteType(FD->getLocation(), ResultType,
9528 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009529 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00009530
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009531 // GNU warning -Wmissing-prototypes:
9532 // Warn if a global function is defined without a previous
9533 // prototype declaration. This warning is issued even if the
9534 // definition itself provides a prototype. The aim is to detect
9535 // global functions that fail to be declared in header files.
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009536 const FunctionDecl *PossibleZeroParamPrototype = 0;
9537 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson9f89dd72009-12-09 03:30:09 +00009538 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithac83a3c2013-06-25 20:34:17 +00009539
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009540 if (PossibleZeroParamPrototype) {
Richard Smithac83a3c2013-06-25 20:34:17 +00009541 // We found a declaration that is not a prototype,
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009542 // but that could be a zero-parameter prototype
Richard Smithac83a3c2013-06-25 20:34:17 +00009543 if (TypeSourceInfo *TI =
9544 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9545 TypeLoc TL = TI->getTypeLoc();
9546 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9547 Diag(PossibleZeroParamPrototype->getLocation(),
9548 diag::note_declaration_not_a_prototype)
9549 << PossibleZeroParamPrototype
9550 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9551 }
Anders Carlsson8a0086c2012-12-18 01:29:20 +00009552 }
9553 }
Douglas Gregor8499f3f2009-03-31 16:35:03 +00009554
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009555 if (FnBodyScope)
9556 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009557
Chris Lattner04421082008-04-08 04:40:51 +00009558 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00009559 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9560 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00009561
9562 // Introduce our parameters into the function scope
9563 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9564 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00009565 Param->setOwningFunction(FD);
9566
Chris Lattner04421082008-04-08 04:40:51 +00009567 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009568 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009569 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00009570
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00009571 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00009572 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009573 }
Chris Lattner04421082008-04-08 04:40:51 +00009574
James Molloy16f1f712012-02-29 10:24:19 +00009575 // If we had any tags defined in the function prototype,
9576 // introduce them into the function scope.
9577 if (FnBodyScope) {
Robert Wilhelm834c0582013-08-09 18:02:13 +00009578 for (ArrayRef<NamedDecl *>::iterator
9579 I = FD->getDeclsInPrototypeScope().begin(),
9580 E = FD->getDeclsInPrototypeScope().end();
9581 I != E; ++I) {
James Molloy16f1f712012-02-29 10:24:19 +00009582 NamedDecl *D = *I;
9583
9584 // Some of these decls (like enums) may have been pinned to the translation unit
9585 // for lack of a real context earlier. If so, remove from the translation unit
9586 // and reattach to the current context.
9587 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9588 // Is the decl actually in the context?
9589 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9590 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9591 if (*DI == D) {
9592 Context.getTranslationUnitDecl()->removeDecl(D);
9593 break;
9594 }
9595 }
9596 // Either way, reassign the lexical decl context to our FunctionDecl.
9597 D->setLexicalDeclContext(CurContext);
9598 }
9599
9600 // If the decl has a non-null name, make accessible in the current scope.
9601 if (!D->getName().empty())
9602 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9603
9604 // Similarly, dive into enums and fish their constants out, making them
9605 // accessible in this scope.
9606 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9607 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9608 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie581deb32012-06-06 20:45:41 +00009609 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy16f1f712012-02-29 10:24:19 +00009610 }
9611 }
9612 }
9613
Richard Smith87162c22012-04-17 22:30:01 +00009614 // Ensure that the function's exception specification is instantiated.
9615 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9616 ResolveExceptionSpec(D->getLocation(), FPT);
9617
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009618 // Checking attributes of current function definition
9619 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00009620 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9621 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9622 // dllimport attribute cannot be directly applied to definition.
Francois Pichetb613cd62011-03-29 10:39:17 +00009623 // Microsoft accepts dllimport for functions defined within class scope.
9624 if (!DA->isInherited() &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00009625 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009626 Diag(FD->getLocation(),
9627 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9628 << "dllimport";
9629 FD->setInvalidDecl();
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009630 return D;
Ted Kremenek12911a82010-02-21 05:12:53 +00009631 }
9632
9633 // Visual C++ appears to not think this is an issue, so only issue
9634 // a warning when Microsoft extensions are disabled.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009635 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009636 // If a symbol previously declared dllimport is later defined, the
9637 // attribute is ignored in subsequent references, and a warning is
9638 // emitted.
9639 Diag(FD->getLocation(),
9640 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00009641 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00009642 }
9643 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +00009644 // We want to attach documentation to original Decl (which might be
9645 // a function template).
9646 ActOnDocumentableDecl(D);
Argyrios Kyrtzidisa9990e82012-12-14 06:54:03 +00009647 return D;
Reid Spencer5f016e22007-07-11 17:01:13 +00009648}
9649
Douglas Gregor5077c382010-05-15 06:01:05 +00009650/// \brief Given the set of return statements within a function body,
9651/// compute the variables that are subject to the named return value
9652/// optimization.
9653///
9654/// Each of the variables that is subject to the named return value
9655/// optimization will be marked as NRVO variables in the AST, and any
9656/// return statement that has a marked NRVO variable as its NRVO candidate can
9657/// use the named return value optimization.
9658///
9659/// This function applies a very simplistic algorithm for NRVO: if every return
9660/// statement in the function has the same NRVO candidate, that candidate is
9661/// the NRVO variable.
9662///
9663/// FIXME: Employ a smarter algorithm that accounts for multiple return
9664/// statements and the lifetimes of the NRVO candidates. We should be able to
9665/// find a maximal set of NRVO variables.
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009666void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCall781472f2010-08-25 08:40:02 +00009667 ReturnStmt **Returns = Scope->Returns.data();
9668
Douglas Gregor5077c382010-05-15 06:01:05 +00009669 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00009670 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00009671 if (!Returns[I]->getNRVOCandidate())
9672 return;
9673
9674 if (!NRVOCandidate)
9675 NRVOCandidate = Returns[I]->getNRVOCandidate();
9676 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9677 return;
9678 }
9679
9680 if (NRVOCandidate)
9681 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9682}
9683
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009684bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smithd1bac8d2012-11-27 21:31:01 +00009685 if (!Consumer.shouldSkipFunctionBody(D))
9686 return false;
9687
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009688 if (isa<ObjCMethodDecl>(D))
9689 return true;
9690
9691 FunctionDecl *FD = 0;
9692 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9693 FD = FTD->getTemplatedDecl();
9694 else
9695 FD = cast<FunctionDecl>(D);
9696
9697 // We cannot skip the body of a function (or function template) which is
9698 // constexpr, since we may need to evaluate its body in order to parse the
9699 // rest of the file.
Richard Smith25d8c852013-05-10 04:31:10 +00009700 // We cannot skip the body of a function with an undeduced return type,
9701 // because any callers of that function need to know the type.
9702 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1a5bd5d2012-11-19 21:13:18 +00009703}
9704
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009705Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009706 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009707 FD->setHasSkippedBody();
Argyrios Kyrtzidis1f12c472013-02-22 04:11:06 +00009708 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis35f3f362012-12-06 18:59:10 +00009709 MD->setHasSkippedBody();
9710 return ActOnFinishFunctionBody(Decl, 0);
9711}
9712
John McCallf312b1e2010-08-26 23:41:50 +00009713Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009714 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009715}
9716
John McCall9ae2f072010-08-23 23:25:46 +00009717Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9718 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00009719 FunctionDecl *FD = 0;
9720 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9721 if (FunTmpl)
9722 FD = FunTmpl->getTemplatedDecl();
9723 else
9724 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9725
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009726 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009727 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009728
Douglas Gregord83d0402009-08-22 00:34:47 +00009729 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00009730 FD->setBody(Body);
John McCall75d8ba32012-02-14 19:50:52 +00009731
Richard Smith25d8c852013-05-10 04:31:10 +00009732 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9733 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9734 // If the function has a deduced result type but contains no 'return'
9735 // statements, the result type as written must be exactly 'auto', and
9736 // the deduced result type is 'void'.
9737 if (!FD->getResultType()->getAs<AutoType>()) {
9738 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9739 << FD->getResultType();
9740 FD->setInvalidDecl();
9741 } else {
9742 // Substitute 'void' for the 'auto' in the type.
9743 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9744 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9745 Context.adjustDeducedFunctionResultType(
9746 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith60e141e2013-05-04 07:00:32 +00009747 }
9748 }
9749
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009750 // The only way to be included in UndefinedButUsed is if there is an
9751 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewycky995e26b2013-01-31 03:23:57 +00009752 // is the first declaration.
Rafael Espindola7693b322013-10-19 02:13:21 +00009753 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00009754 if (!FD->isExternallyVisible())
Nick Lewyckycd0655b2013-02-01 08:13:20 +00009755 UndefinedButUsed.erase(FD);
9756 else if (FD->isInlined() &&
9757 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9758 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9759 UndefinedButUsed.erase(FD);
9760 }
Nick Lewycky995e26b2013-01-31 03:23:57 +00009761
John McCall75d8ba32012-02-14 19:50:52 +00009762 // If the function implicitly returns zero (like 'main') or is naked,
9763 // don't complain about missing return statements.
9764 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenekd064fdc2010-03-23 00:13:23 +00009765 WP.disableCheckFallThrough();
Mike Stump1eb44332009-09-09 15:08:12 +00009766
Francois Pichet6a247472011-05-11 02:14:46 +00009767 // MSVC permits the use of pure specifier (=0) on function definition,
9768 // defined at class scope, warn about this non standard construct.
Reid Kleckner5dbed662013-10-08 22:45:29 +00009769 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet6a247472011-05-11 02:14:46 +00009770 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9771
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009772 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009773 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009774 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9775 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009776
9777 // If this is a constructor, we need a vtable.
9778 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9779 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00009780
Jordan Rose7dd900e2012-07-02 21:19:23 +00009781 // Try to apply the named return value optimization. We have to check
9782 // if we can do this here because lambdas keep return statements around
9783 // to deduce an implicit return type.
9784 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9785 !FD->isDependentContext())
9786 computeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009787 }
9788
Douglas Gregor76e3da52012-02-08 20:17:14 +00009789 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9790 "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00009791 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00009792 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00009793 MD->setBody(Body);
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009794 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00009795 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009796 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9797 MD->getResultType(), MD);
Douglas Gregorf7603f62011-09-06 20:33:37 +00009798
9799 if (Body)
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009800 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00009801 }
Jordan Rose535a5d02012-10-19 16:05:26 +00009802 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanian9f559832012-09-10 16:51:09 +00009803 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9804 << MD->getSelector().getAsString();
Jordan Rose535a5d02012-10-19 16:05:26 +00009805 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00009806 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00009807 } else {
John McCalld226f652010-08-21 09:40:31 +00009808 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00009809 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00009810
Jordan Rose535a5d02012-10-19 16:05:26 +00009811 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman95aac152012-08-01 21:02:59 +00009812 "This should only be set for ObjC methods, which should have been "
9813 "handled in the block above.");
Nico Weber9a1ecf02011-08-22 17:25:57 +00009814
Reid Spencer5f016e22007-07-11 17:01:13 +00009815 // Verify and clean out per-function state.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009816 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009817 // C++ constructors that have function-try-blocks can't have return
9818 // statements in the handlers of that block. (C++ [except.handle]p14)
9819 // Verify this.
9820 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9821 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9822
Richard Smith37bee672011-08-12 18:44:32 +00009823 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00009824 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00009825 !dcl->isInvalidDecl() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009826 !hasAnyUnrecoverableErrorsInThisFunction() &&
9827 !PP.isCodeCompletionEnabled())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009828 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00009829
John McCall15442822010-08-04 01:04:25 +00009830 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9831 if (!Destructor->getParent()->isDependentType())
9832 CheckDestructor(Destructor);
9833
John McCallef027fe2010-03-16 21:39:52 +00009834 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9835 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00009836 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009837
9838 // If any errors have occurred, clear out any temporaries that may have
9839 // been leftover. This ensures that these temporaries won't be picked up for
9840 // deletion in some later function.
Douglas Gregor26cd44d2011-03-04 23:08:02 +00009841 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCallf85e1932011-06-15 23:02:42 +00009842 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall80ee6e82011-11-10 05:35:25 +00009843 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins12f37e42012-12-07 22:53:48 +00009844 }
9845 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9846 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009847 // Since the body is valid, issue any analysis-based warnings that are
9848 // enabled.
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009849 ActivePolicy = &WP;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00009850 }
9851
Richard Smith86c3ae42012-02-13 03:54:03 +00009852 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9853 (!CheckConstexprFunctionDecl(FD) ||
9854 !CheckConstexprFunctionBody(FD, Body)))
Richard Smith9f569cc2011-10-01 02:31:28 +00009855 FD->setInvalidDecl();
9856
John McCall80ee6e82011-11-10 05:35:25 +00009857 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCallf85e1932011-06-15 23:02:42 +00009858 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedmand2cce132012-02-02 23:15:15 +00009859 assert(MaybeODRUseExprs.empty() &&
9860 "Leftover expressions for odr-use checking");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009861 }
9862
John McCall90f97892010-03-25 22:08:03 +00009863 if (!IsInstantiation)
9864 PopDeclContext();
9865
Eli Friedmanec9ea722012-01-05 03:35:19 +00009866 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregord5b57282009-11-15 07:07:58 +00009867 // If any errors have occurred, clear out any temporaries that may have
9868 // been leftover. This ensures that these temporaries won't be picked up for
9869 // deletion in some later function.
John McCallf85e1932011-06-15 23:02:42 +00009870 if (getDiagnostics().hasErrorOccurred()) {
John McCall80ee6e82011-11-10 05:35:25 +00009871 DiscardCleanupsInEvaluationContext();
John McCallf85e1932011-06-15 23:02:42 +00009872 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00009873
John McCalld226f652010-08-21 09:40:31 +00009874 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00009875}
9876
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009877
9878/// When we finish delayed parsing of an attribute, we must attach it to the
9879/// relevant Decl.
9880void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9881 ParsedAttributes &Attrs) {
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +00009882 // Always attach attributes to the underlying decl.
9883 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9884 D = TD->getTemplatedDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00009885 ProcessDeclAttributeList(S, D, Attrs.getList());
9886
9887 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9888 if (Method->isStatic())
9889 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +00009890}
9891
9892
Reid Spencer5f016e22007-07-11 17:01:13 +00009893/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9894/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00009895NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00009896 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00009897 // Before we produce a declaration for an implicitly defined
9898 // function, see whether there was a locally-scoped declaration of
9899 // this name as a function or variable. If so, use that
9900 // (non-visible) declaration, and complain about it.
Richard Smith662f41b2013-06-18 20:15:12 +00009901 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9902 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9903 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9904 return ExternCPrev;
Douglas Gregor63935192009-03-02 00:19:53 +00009905 }
9906
Chris Lattner37d10842008-05-05 21:18:06 +00009907 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009908 unsigned diag_id;
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00009909 if (II.getName().startswith("__builtin_"))
Abramo Bagnara753a2002012-01-09 10:05:48 +00009910 diag_id = diag::warn_builtin_unknown;
David Blaikie4e4d0842012-03-11 07:00:24 +00009911 else if (getLangOpts().C99)
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009912 diag_id = diag::ext_implicit_function_decl;
Chris Lattner37d10842008-05-05 21:18:06 +00009913 else
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009914 diag_id = diag::warn_implicit_function_decl;
9915 Diag(Loc, diag_id) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00009916
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009917 // Because typo correction is expensive, only do it if the implicit
9918 // function declaration is going to be treated as an error.
9919 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9920 TypoCorrection Corrected;
Kaelyn Uhrain43e875d2012-01-18 21:41:41 +00009921 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborge3ca33a2011-12-08 15:56:07 +00009922 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smith2d670972013-08-17 00:46:16 +00009923 LookupOrdinaryName, S, 0, Validator)))
9924 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9925 /*ErrorRecovery*/false);
Hans Wennborg122de3e2011-12-06 09:46:12 +00009926 }
9927
Reid Spencer5f016e22007-07-11 17:01:13 +00009928 // Set a Declarator for the implicit definition: int foo();
9929 const char *Dummy;
John McCall0b7e6782011-03-24 11:26:52 +00009930 AttributeFactory attrFactory;
9931 DeclSpec DS(attrFactory);
John McCallfec54012009-08-03 20:12:06 +00009932 unsigned DiagID;
9933 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00009934 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00009935 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009936 SourceLocation NoLoc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009937 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnara59c0a812012-10-04 21:42:10 +00009938 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9939 /*IsAmbiguous=*/false,
9940 /*RParenLoc=*/NoLoc,
9941 /*ArgInfo=*/0,
9942 /*NumArgs=*/0,
9943 /*EllipsisLoc=*/NoLoc,
9944 /*RParenLoc=*/NoLoc,
9945 /*TypeQuals=*/0,
9946 /*RefQualifierIsLvalueRef=*/true,
9947 /*RefQualifierLoc=*/NoLoc,
9948 /*ConstQualifierLoc=*/NoLoc,
9949 /*VolatileQualifierLoc=*/NoLoc,
9950 /*MutableLoc=*/NoLoc,
9951 EST_None,
9952 /*ESpecLoc=*/NoLoc,
9953 /*Exceptions=*/0,
9954 /*ExceptionRanges=*/0,
9955 /*NumExceptions=*/0,
9956 /*NoexceptExpr=*/0,
9957 Loc, Loc, D),
John McCall0b7e6782011-03-24 11:26:52 +00009958 DS.getAttributes(),
Sebastian Redlab197ba2009-02-09 18:23:29 +00009959 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00009960 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00009961
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009962 // Insert this function into translation-unit scope.
9963
9964 DeclContext *PrevDC = CurContext;
9965 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009966
Jordan Rose41f3f3a2013-03-05 01:27:54 +00009967 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00009968 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00009969
9970 CurContext = PrevDC;
9971
Douglas Gregor3c385e52009-02-14 18:57:46 +00009972 AddKnownFunctionAttributes(FD);
9973
Steve Naroffe2ef8152008-04-04 14:32:09 +00009974 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00009975}
9976
Douglas Gregor3c385e52009-02-14 18:57:46 +00009977/// \brief Adds any function attributes that we know a priori based on
9978/// the declaration of this function.
9979///
9980/// These attributes can apply both to implicitly-declared builtins
9981/// (like __builtin___printf_chk) or to library-declared functions
9982/// like NSLog or printf.
Douglas Gregorb30cd4a2011-06-15 05:45:11 +00009983///
9984/// We need to check for duplicate attributes both here and where user-written
9985/// attributes are applied to declarations.
Douglas Gregor3c385e52009-02-14 18:57:46 +00009986void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9987 if (FD->isInvalidDecl())
9988 return;
9989
9990 // If this is a built-in function, map its builtin attributes to
9991 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00009992 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00009993 // Handle printf-formatting attributes.
9994 unsigned FormatIdx;
9995 bool HasVAListArg;
9996 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +00009997 if (!FD->getAttr<FormatAttr>()) {
9998 const char *fmt = "printf";
9999 unsigned int NumParams = FD->getNumParams();
10000 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10001 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10002 fmt = "NSString";
Sean Huntcf807c42010-08-18 23:23:40 +000010003 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010004 &Context.Idents.get(fmt),
10005 FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +000010006 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010007 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010008 }
Ted Kremenekbee05c12010-07-16 02:11:15 +000010009 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10010 HasVAListArg)) {
10011 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010012 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010013 &Context.Idents.get("scanf"),
10014 FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +000010015 HasVAListArg ? 0 : FormatIdx+2));
10016 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010017
10018 // Mark const if we don't care about errno and that is the only
10019 // thing preventing the function from being const. This allows
10020 // IRgen to use LLVM intrinsics for such functions.
David Blaikie4e4d0842012-03-11 07:00:24 +000010021 if (!getLangOpts().MathErrno &&
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010022 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010023 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010024 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +000010025 }
Mike Stump0feecbb2009-07-27 19:14:18 +000010026
Rafael Espindola67004152011-10-12 19:51:18 +000010027 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10028 !FD->getAttr<ReturnsTwiceAttr>())
10029 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010030 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010031 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregorb30cd4a2011-06-15 05:45:11 +000010032 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010033 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +000010034 }
10035
10036 IdentifierInfo *Name = FD->getIdentifier();
10037 if (!Name)
10038 return;
David Blaikie4e4d0842012-03-11 07:00:24 +000010039 if ((!getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +000010040 FD->getDeclContext()->isTranslationUnit()) ||
10041 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +000010042 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +000010043 LinkageSpecDecl::lang_c)) {
10044 // Okay: this could be a libc/libm/Objective-C function we know
10045 // about.
10046 } else
10047 return;
10048
Jean-Daniel Dupas1acbe5e2012-01-24 22:32:46 +000010049 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +000010050 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +000010051 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000010052 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +000010053 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmancaa5ab22013-09-03 21:02:22 +000010054 &Context.Idents.get("printf"), 2,
Eli Friedmand7dad722009-06-10 04:01:38 +000010055 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +000010056 }
Jordan Rose8a64f882012-08-08 21:17:31 +000010057
10058 if (Name->isStr("__CFStringMakeConstantString")) {
10059 // We already have a __builtin___CFStringMakeConstantString,
10060 // but builds that use -fno-constant-cfstrings don't go through that.
10061 if (!FD->getAttr<FormatArgAttr>())
10062 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10063 }
Douglas Gregor3c385e52009-02-14 18:57:46 +000010064}
Reid Spencer5f016e22007-07-11 17:01:13 +000010065
John McCallba6a9bd2009-10-24 08:00:42 +000010066TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000010067 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010068 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +000010069 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +000010070
John McCalla93c9342009-12-07 02:54:59 +000010071 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +000010072 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +000010073 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +000010074 }
10075
Reid Spencer5f016e22007-07-11 17:01:13 +000010076 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +000010077 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010078 D.getLocStart(),
Chris Lattner0ed844b2008-04-04 06:12:32 +000010079 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +000010080 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +000010081 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +000010082
John McCallcde5a402011-02-01 08:20:08 +000010083 // Bail out immediately if we have an invalid declaration.
10084 if (D.isInvalidType()) {
10085 NewTD->setInvalidDecl();
10086 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +000010087 }
10088
Douglas Gregore3895852011-09-12 18:37:38 +000010089 if (D.getDeclSpec().isModulePrivateSpecified()) {
10090 if (CurContext->isFunctionOrMethod())
10091 Diag(NewTD->getLocation(), diag::err_module_private_local)
10092 << 2 << NewTD->getDeclName()
10093 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10094 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10095 else
10096 NewTD->setModulePrivate();
10097 }
Douglas Gregor8d267c52011-09-09 02:06:17 +000010098
John McCallcde5a402011-02-01 08:20:08 +000010099 // C++ [dcl.typedef]p8:
10100 // If the typedef declaration defines an unnamed class (or
10101 // enum), the first typedef-name declared by the declaration
10102 // to be that class type (or enum type) is used to denote the
10103 // class type (or enum type) for linkage purposes only.
10104 // We need to check whether the type was declared in the declaration.
10105 switch (D.getDeclSpec().getTypeSpecType()) {
10106 case TST_enum:
10107 case TST_struct:
Joao Matos6666ed42012-08-31 18:45:21 +000010108 case TST_interface:
John McCallcde5a402011-02-01 08:20:08 +000010109 case TST_union:
10110 case TST_class: {
10111 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10112
10113 // Do nothing if the tag is not anonymous or already has an
10114 // associated typedef (from an earlier typedef in this decl group).
10115 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smith162e1c12011-04-15 14:24:37 +000010116 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCallcde5a402011-02-01 08:20:08 +000010117
10118 // A well-formed anonymous tag must always be a TUK_Definition.
10119 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10120
10121 // The type must match the tag exactly; no qualifiers allowed.
10122 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10123 break;
10124
10125 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smith162e1c12011-04-15 14:24:37 +000010126 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCallcde5a402011-02-01 08:20:08 +000010127 break;
10128 }
10129
10130 default:
10131 break;
10132 }
10133
Steve Naroff5912a352007-08-28 20:14:24 +000010134 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +000010135}
10136
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010137
Richard Smithf1c66b42012-03-14 23:13:10 +000010138/// \brief Check that this is a valid underlying type for an enum declaration.
10139bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10140 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10141 QualType T = TI->getType();
10142
Eli Friedman2fcff832012-12-18 02:37:32 +000010143 if (T->isDependentType())
Richard Smithf1c66b42012-03-14 23:13:10 +000010144 return false;
10145
Eli Friedman2fcff832012-12-18 02:37:32 +000010146 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10147 if (BT->isInteger())
10148 return false;
10149
Richard Smithf1c66b42012-03-14 23:13:10 +000010150 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10151 return true;
10152}
10153
10154/// Check whether this is a valid redeclaration of a previous enumeration.
10155/// \return true if the redeclaration was invalid.
10156bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10157 QualType EnumUnderlyingTy,
10158 const EnumDecl *Prev) {
10159 bool IsFixed = !EnumUnderlyingTy.isNull();
10160
10161 if (IsScoped != Prev->isScoped()) {
10162 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10163 << Prev->isScoped();
10164 Diag(Prev->getLocation(), diag::note_previous_use);
10165 return true;
10166 }
10167
10168 if (IsFixed && Prev->isFixed()) {
Richard Smith4ca93d92012-03-26 04:08:46 +000010169 if (!EnumUnderlyingTy->isDependentType() &&
10170 !Prev->getIntegerType()->isDependentType() &&
10171 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smithf1c66b42012-03-14 23:13:10 +000010172 Prev->getIntegerType())) {
10173 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10174 << EnumUnderlyingTy << Prev->getIntegerType();
10175 Diag(Prev->getLocation(), diag::note_previous_use);
10176 return true;
10177 }
10178 } else if (IsFixed != Prev->isFixed()) {
10179 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10180 << Prev->isFixed();
10181 Diag(Prev->getLocation(), diag::note_previous_use);
10182 return true;
10183 }
10184
10185 return false;
10186}
10187
Joao Matos6666ed42012-08-31 18:45:21 +000010188/// \brief Get diagnostic %select index for tag kind for
10189/// redeclaration diagnostic message.
10190/// WARNING: Indexes apply to particular diagnostics only!
10191///
10192/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +000010193static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +000010194 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +000010195 case TTK_Struct: return 0;
10196 case TTK_Interface: return 1;
10197 case TTK_Class: return 2;
10198 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +000010199 }
Joao Matos6666ed42012-08-31 18:45:21 +000010200}
10201
10202/// \brief Determine if tag kind is a class-key compatible with
10203/// class for redeclaration (class, struct, or __interface).
10204///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000010205/// \returns true iff the tag kind is compatible.
Joao Matos6666ed42012-08-31 18:45:21 +000010206static bool isClassCompatTagKind(TagTypeKind Tag)
10207{
10208 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10209}
10210
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010211/// \brief Determine whether a tag with a given kind is acceptable
10212/// as a redeclaration of the given tag declaration.
10213///
10214/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +000010215bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieubbf34c02011-06-10 03:11:26 +000010216 TagTypeKind NewTag, bool isDefinition,
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010217 SourceLocation NewTagLoc,
10218 const IdentifierInfo &Name) {
10219 // C++ [dcl.type.elab]p3:
10220 // The class-key or enum keyword present in the
10221 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010222 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010223 // refers. This rule also applies to the form of
10224 // elaborated-type-specifier that declares a class-name or
10225 // friend class since it can be construed as referring to the
10226 // definition of the class. Thus, in any
10227 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010228 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010229 // used to refer to a union (clause 9), and either the class or
10230 // struct class-key shall be used to refer to a class (clause 9)
10231 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010232 TagTypeKind OldTag = Previous->getTagKind();
Joao Matos6666ed42012-08-31 18:45:21 +000010233 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieubbf34c02011-06-10 03:11:26 +000010234 if (OldTag == NewTag)
10235 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010236
Joao Matos6666ed42012-08-31 18:45:21 +000010237 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010238 // Warn about the struct/class tag mismatch.
10239 bool isTemplate = false;
10240 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10241 isTemplate = Record->getDescribedClassTemplate();
10242
Richard Trieubbf34c02011-06-10 03:11:26 +000010243 if (!ActiveTemplateInstantiations.empty()) {
10244 // In a template instantiation, do not offer fix-its for tag mismatches
10245 // since they usually mess up the template instead of fixing the problem.
10246 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010247 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10248 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010249 return true;
10250 }
10251
10252 if (isDefinition) {
10253 // On definitions, check previous tags and issue a fix-it for each
10254 // one that doesn't match the current tag.
10255 if (Previous->getDefinition()) {
10256 // Don't suggest fix-its for redefinitions.
10257 return true;
10258 }
10259
10260 bool previousMismatch = false;
10261 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10262 E(Previous->redecls_end()); I != E; ++I) {
10263 if (I->getTagKind() != NewTag) {
10264 if (!previousMismatch) {
10265 previousMismatch = true;
10266 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010267 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10268 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieubbf34c02011-06-10 03:11:26 +000010269 }
10270 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010271 << getRedeclDiagFromTagKind(NewTag)
Richard Trieubbf34c02011-06-10 03:11:26 +000010272 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matos6666ed42012-08-31 18:45:21 +000010273 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieubbf34c02011-06-10 03:11:26 +000010274 }
10275 }
10276 return true;
10277 }
10278
10279 // Check for a previous definition. If current tag and definition
10280 // are same type, do nothing. If no definition, but disagree with
10281 // with previous tag type, give a warning, but no fix-it.
10282 const TagDecl *Redecl = Previous->getDefinition() ?
10283 Previous->getDefinition() : Previous;
10284 if (Redecl->getTagKind() == NewTag) {
10285 return true;
10286 }
10287
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010288 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matos6666ed42012-08-31 18:45:21 +000010289 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10290 << getRedeclDiagFromTagKind(OldTag);
Richard Trieubbf34c02011-06-10 03:11:26 +000010291 Diag(Redecl->getLocation(), diag::note_previous_use);
10292
10293 // If there is a previous defintion, suggest a fix-it.
10294 if (Previous->getDefinition()) {
10295 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matos6666ed42012-08-31 18:45:21 +000010296 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieubbf34c02011-06-10 03:11:26 +000010297 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matos6666ed42012-08-31 18:45:21 +000010298 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieubbf34c02011-06-10 03:11:26 +000010299 }
10300
Douglas Gregor501c5ce2009-05-14 16:41:31 +000010301 return true;
10302 }
10303 return false;
10304}
10305
Steve Naroff08d92e42007-09-15 18:49:24 +000010306/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +000010307/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +000010308/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +000010309/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +000010310Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +000010311 SourceLocation KWLoc, CXXScopeSpec &SS,
10312 IdentifierInfo *Name, SourceLocation NameLoc,
10313 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010314 SourceLocation ModulePrivateLoc,
Douglas Gregor069ea642010-09-16 23:58:57 +000010315 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010316 bool &OwnedDecl, bool &IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010317 SourceLocation ScopedEnumKWLoc,
10318 bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010319 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010320 // If this is not a definition, it must have a name.
Douglas Gregor69605872012-03-28 16:01:27 +000010321 IdentifierInfo *OrigName = Name;
John McCall0f434ec2009-07-31 02:45:11 +000010322 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000010323 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +000010324 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010325
Douglas Gregor402abb52009-05-28 23:31:59 +000010326 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010327 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smithbdad7a22012-01-10 01:33:14 +000010328 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump1eb44332009-09-09 15:08:12 +000010329
Douglas Gregor1fef4e62009-10-07 22:35:40 +000010330 // FIXME: Check explicit specializations more carefully.
10331 bool isExplicitSpecialization = false;
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010332 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +000010333
10334 // We only need to do this matching if we have template parameters
10335 // or a scope specifier, which also conveniently avoids this work
10336 // for non-C++ cases.
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010337 if (TemplateParameterLists.size() > 0 ||
John McCall9a34edb2010-10-19 01:40:49 +000010338 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000010339 if (TemplateParameterList *TemplateParams =
10340 MatchTemplateParametersToScopeSpecifier(
10341 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10342 isExplicitSpecialization, Invalid)) {
Richard Smith725fe0e2013-04-01 21:43:41 +000010343 if (Kind == TTK_Enum) {
10344 Diag(KWLoc, diag::err_enum_template);
10345 return 0;
10346 }
10347
Douglas Gregord85bea22009-09-26 06:47:28 +000010348 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010349 // This is a declaration or definition of a class template (which may
10350 // be a member of another template).
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010351
Douglas Gregor0167f3c2010-07-14 23:14:12 +000010352 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +000010353 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010354
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010355 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +000010356 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010357 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010358 TemplateParams, AS,
Douglas Gregore7612302011-09-09 19:05:14 +000010359 ModulePrivateLoc,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010360 TemplateParameterLists.size()-1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010361 TemplateParameterLists.data());
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010362 return Result.get();
10363 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +000010364 // The "template<>" header is extraneous.
10365 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010366 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +000010367 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +000010368 }
Mike Stump1eb44332009-09-09 15:08:12 +000010369 }
10370 }
10371
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010372 // Figure out the underlying type if this a enum declaration. We need to do
10373 // this early, because it's needed to detect if this is an incompatible
10374 // redeclaration.
10375 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10376
10377 if (Kind == TTK_Enum) {
10378 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10379 // No underlying type explicitly specified, or we failed to parse the
10380 // type, default to int.
10381 EnumUnderlying = Context.IntTy.getTypePtr();
10382 else if (UnderlyingType.get()) {
10383 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10384 // integral type; any cv-qualification is ignored.
10385 TypeSourceInfo *TI = 0;
Richard Smith878416d2012-03-15 00:22:18 +000010386 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010387 EnumUnderlying = TI;
10388
Richard Smithf1c66b42012-03-14 23:13:10 +000010389 if (CheckEnumUnderlyingType(TI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010390 // Recover by falling back to int.
10391 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010392
Richard Smithf1c66b42012-03-14 23:13:10 +000010393 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor0c9e4792010-12-16 00:24:44 +000010394 UPPC_FixedUnderlyingType))
10395 EnumUnderlying = Context.IntTy.getTypePtr();
10396
David Blaikie4e4d0842012-03-11 07:00:24 +000010397 } else if (getLangOpts().MicrosoftMode)
Francois Pichet842e7a22010-10-18 15:01:13 +000010398 // Microsoft enums are always of int type.
10399 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010400 }
10401
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010402 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010403 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010404 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010405
Chandler Carruth7bf36002010-03-01 21:17:36 +000010406 RedeclarationKind Redecl = ForRedeclaration;
10407 if (TUK == TUK_Friend || TUK == TUK_Reference)
10408 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +000010409
10410 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregord9433522013-06-27 20:42:30 +000010411 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010412 if (Name && SS.isNotEmpty()) {
10413 // We have a nested-name tag ('struct foo::bar').
10414
10415 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010416 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010417 Name = 0;
10418 goto CreateNewDecl;
10419 }
10420
John McCallc4e70192009-09-11 04:59:25 +000010421 // If this is a friend or a reference to a class in a dependent
10422 // context, don't try to make a decl for it.
10423 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10424 DC = computeDeclContext(SS, false);
10425 if (!DC) {
10426 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010427 return 0;
John McCallc4e70192009-09-11 04:59:25 +000010428 }
John McCall77bb1aa2010-05-01 00:40:08 +000010429 } else {
10430 DC = computeDeclContext(SS, true);
10431 if (!DC) {
10432 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10433 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +000010434 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +000010435 }
John McCallc4e70192009-09-11 04:59:25 +000010436 }
10437
John McCall77bb1aa2010-05-01 00:40:08 +000010438 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +000010439 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +000010440
Douglas Gregor1931b442009-02-03 00:34:39 +000010441 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +000010442 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +000010443 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +000010444
John McCall68263142009-11-18 22:49:29 +000010445 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010446 return 0;
John McCall6e247262009-10-10 05:48:19 +000010447
John McCall68263142009-11-18 22:49:29 +000010448 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010449 // Name lookup did not find anything. However, if the
10450 // nested-name-specifier refers to the current instantiation,
10451 // and that current instantiation has any dependent base
10452 // classes, we might find something at instantiation time: treat
10453 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +000010454 // But this only makes any sense for reference-like lookups.
10455 if (Previous.wasNotFoundInCurrentInstantiation() &&
10456 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010457 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +000010458 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +000010459 }
10460
10461 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +000010462 Diag(NameLoc, diag::err_not_tag_in_scope)
10463 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010464 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +000010465 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010466 goto CreateNewDecl;
10467 }
Chris Lattnercf79b012009-01-21 02:38:50 +000010468 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010469 // If this is a named struct, check to see if there was a previous forward
10470 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +000010471 // FIXME: We're looking into outer scopes here, even when we
10472 // shouldn't be. Doing so can result in ambiguities that we
10473 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +000010474 LookupName(Previous, S);
10475
John McCallc96cd7a2013-03-20 01:53:00 +000010476 // When declaring or defining a tag, ignore ambiguities introduced
10477 // by types using'ed into this scope.
Douglas Gregor93b6bce2011-05-09 21:46:33 +000010478 if (Previous.isAmbiguous() &&
10479 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregor61c6c442011-05-04 00:25:33 +000010480 LookupResult::Filter F = Previous.makeFilter();
10481 while (F.hasNext()) {
10482 NamedDecl *ND = F.next();
10483 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10484 F.erase();
10485 }
10486 F.done();
Douglas Gregor61c6c442011-05-04 00:25:33 +000010487 }
John McCallc96cd7a2013-03-20 01:53:00 +000010488
10489 // C++11 [namespace.memdef]p3:
10490 // If the name in a friend declaration is neither qualified nor
10491 // a template-id and the declaration is a function or an
10492 // elaborated-type-specifier, the lookup to determine whether
10493 // the entity has been previously declared shall not consider
10494 // any scopes outside the innermost enclosing namespace.
10495 //
10496 // Does it matter that this should be by scope instead of by
10497 // semantic context?
10498 if (!Previous.empty() && TUK == TUK_Friend) {
10499 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10500 LookupResult::Filter F = Previous.makeFilter();
10501 while (F.hasNext()) {
10502 NamedDecl *ND = F.next();
10503 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregord9433522013-06-27 20:42:30 +000010504 if (DC->isFileContext() &&
10505 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCallc96cd7a2013-03-20 01:53:00 +000010506 F.erase();
Douglas Gregord9433522013-06-27 20:42:30 +000010507 FriendSawTagOutsideEnclosingNamespace = true;
10508 }
John McCallc96cd7a2013-03-20 01:53:00 +000010509 }
10510 F.done();
10511 }
Douglas Gregor61c6c442011-05-04 00:25:33 +000010512
John McCall68263142009-11-18 22:49:29 +000010513 // Note: there used to be some attempt at recovery here.
10514 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +000010515 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +000010516
David Blaikie4e4d0842012-03-11 07:00:24 +000010517 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +000010518 // FIXME: This makes sure that we ignore the contexts associated
10519 // with C structs, unions, and enums when looking for a matching
10520 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +000010521 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +000010522 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10523 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +000010524 }
Douglas Gregor069ea642010-09-16 23:58:57 +000010525 } else if (S->isFunctionPrototypeScope()) {
10526 // If this is an enum declaration in function prototype scope, set its
10527 // initial context to the translation unit.
Nick Lewycky8d176812012-03-10 07:45:33 +000010528 // FIXME: [citation needed]
Douglas Gregor069ea642010-09-16 23:58:57 +000010529 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +000010530 }
10531
John McCall68263142009-11-18 22:49:29 +000010532 if (Previous.isSingleResult() &&
10533 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000010534 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +000010535 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +000010536 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +000010537 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +000010538 }
10539
David Blaikie4e4d0842012-03-11 07:00:24 +000010540 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010541 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010542 // This is a declaration of or a reference to "std::bad_alloc".
10543 isStdBadAlloc = true;
10544
John McCall68263142009-11-18 22:49:29 +000010545 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010546 // std::bad_alloc has been implicitly declared (but made invisible to
10547 // name lookup). Fill in this implicit declaration as the previous
10548 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010549 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010550 }
10551 }
John McCall68263142009-11-18 22:49:29 +000010552
John McCall9c86b512010-03-25 21:28:06 +000010553 // If we didn't find a previous declaration, and this is a reference
10554 // (or friend reference), move to the correct scope. In C++, we
10555 // also need to do a redeclaration lookup there, just in case
10556 // there's a shadow friend decl.
10557 if (Name && Previous.empty() &&
10558 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10559 if (Invalid) goto CreateNewDecl;
10560 assert(SS.isEmpty());
10561
10562 if (TUK == TUK_Reference) {
10563 // C++ [basic.scope.pdecl]p5:
10564 // -- for an elaborated-type-specifier of the form
10565 //
10566 // class-key identifier
10567 //
10568 // if the elaborated-type-specifier is used in the
10569 // decl-specifier-seq or parameter-declaration-clause of a
10570 // function defined in namespace scope, the identifier is
10571 // declared as a class-name in the namespace that contains
10572 // the declaration; otherwise, except as a friend
10573 // declaration, the identifier is declared in the smallest
10574 // non-class, non-function-prototype scope that contains the
10575 // declaration.
10576 //
10577 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10578 // C structs and unions.
10579 //
10580 // It is an error in C++ to declare (rather than define) an enum
10581 // type, including via an elaborated type specifier. We'll
10582 // diagnose that later; for now, declare the enum in the same
10583 // scope as we would have picked for any other tag type.
10584 //
10585 // GNU C also supports this behavior as part of its incomplete
10586 // enum types extension, while GNU C++ does not.
10587 //
10588 // Find the context where we'll be declaring the tag.
10589 // FIXME: We would like to maintain the current DeclContext as the
10590 // lexical context,
Nick Lewycky1659c372012-03-10 07:47:07 +000010591 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCall9c86b512010-03-25 21:28:06 +000010592 SearchDC = SearchDC->getParent();
10593
10594 // Find the scope where we'll be declaring the tag.
10595 while (S->isClassScope() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010596 (getLangOpts().CPlusPlus &&
John McCall9c86b512010-03-25 21:28:06 +000010597 S->isFunctionPrototypeScope()) ||
10598 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekf0d58612013-10-08 17:08:03 +000010599 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCall9c86b512010-03-25 21:28:06 +000010600 S = S->getParent();
10601 } else {
10602 assert(TUK == TUK_Friend);
10603 // C++ [namespace.memdef]p3:
10604 // If a friend declaration in a non-local class first declares a
10605 // class or function, the friend class or function is a member of
10606 // the innermost enclosing namespace.
10607 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +000010608 }
10609
John McCall0d6b1642010-04-23 18:46:30 +000010610 // In C++, we need to do a redeclaration lookup to properly
10611 // diagnose some problems.
David Blaikie4e4d0842012-03-11 07:00:24 +000010612 if (getLangOpts().CPlusPlus) {
John McCall9c86b512010-03-25 21:28:06 +000010613 Previous.setRedeclarationKind(ForRedeclaration);
10614 LookupQualifiedName(Previous, SearchDC);
10615 }
10616 }
10617
John McCall68263142009-11-18 22:49:29 +000010618 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +000010619 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +000010620
10621 // It's okay to have a tag decl in the same scope as a typedef
10622 // which hides a tag decl in the same scope. Finding this
10623 // insanity with a redeclaration lookup can only actually happen
10624 // in C++.
10625 //
10626 // This is also okay for elaborated-type-specifiers, which is
10627 // technically forbidden by the current standard but which is
10628 // okay according to the likely resolution of an open issue;
10629 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikie4e4d0842012-03-11 07:00:24 +000010630 if (getLangOpts().CPlusPlus) {
Richard Smith162e1c12011-04-15 14:24:37 +000010631 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCall0d6b1642010-04-23 18:46:30 +000010632 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10633 TagDecl *Tag = TT->getDecl();
10634 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000010635 Tag->getDeclContext()->getRedeclContext()
10636 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +000010637 PrevDecl = Tag;
10638 Previous.clear();
10639 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +000010640 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +000010641 }
10642 }
10643 }
10644 }
10645
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010646 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010647 // If this is a use of a previous tag, or if the tag is already declared
10648 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010649 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +000010650 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregorcc209452011-03-07 16:54:27 +000010651 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner14943b92008-07-03 03:30:58 +000010652 // Make sure that this wasn't declared as an enum and now used as a
10653 // struct or something similar.
Richard Trieubbf34c02011-06-10 03:11:26 +000010654 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10655 TUK == TUK_Definition, KWLoc,
10656 *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +000010657 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010658 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10659 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +000010660 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +000010661 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +000010662 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +000010663 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10664 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +000010665 else
10666 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +000010667 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +000010668
Mike Stump1eb44332009-09-09 15:08:12 +000010669 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +000010670 Kind = PrevTagDecl->getTagKind();
10671 else {
10672 // Recover by making this an anonymous redefinition.
10673 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010674 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +000010675 Invalid = true;
10676 }
10677 }
10678
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010679 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10680 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10681
Richard Smithbdad7a22012-01-10 01:33:14 +000010682 // If this is an elaborated-type-specifier for a scoped enumeration,
10683 // the 'class' keyword is not necessary and not permitted.
10684 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10685 if (ScopedEnum)
10686 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10687 << PrevEnum->isScoped()
10688 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10689 return PrevTagDecl;
10690 }
10691
Richard Smithf1c66b42012-03-14 23:13:10 +000010692 QualType EnumUnderlyingTy;
10693 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10694 EnumUnderlyingTy = TI->getType();
10695 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10696 EnumUnderlyingTy = QualType(T, 0);
10697
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010698 // All conflicts with previous declarations are recovered by
Richard Smith3343fad2012-03-23 23:09:08 +000010699 // returning the previous declaration, unless this is a definition,
10700 // in which case we want the caller to bail out.
Richard Smithf1c66b42012-03-14 23:13:10 +000010701 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10702 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smith3343fad2012-03-23 23:09:08 +000010703 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010704 }
10705
David Majnemer2ec2b842013-06-11 03:51:23 +000010706 // C++11 [class.mem]p1:
David Majnemer0f9b8552013-06-11 06:19:45 +000010707 // A member shall not be declared twice in the member-specification,
David Majnemer2ec2b842013-06-11 03:51:23 +000010708 // except that a nested class or member class template can be declared
10709 // and then later defined.
10710 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10711 S->isDeclScope(PrevDecl)) {
10712 Diag(NameLoc, diag::ext_member_redeclared);
10713 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10714 }
10715
Douglas Gregora3a83512009-04-01 23:51:29 +000010716 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010717 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +000010718
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010719 // FIXME: In the future, return a variant or some other clue
10720 // for the consumer of this Decl to know it doesn't own it.
10721 // For our current ASTs this shouldn't be a problem, but will
10722 // need to be changed with DeclGroups.
Francois Pichetb4746032011-06-01 04:14:20 +000010723 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikie4e4d0842012-03-11 07:00:24 +000010724 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +000010725 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +000010726
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010727 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +000010728 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +000010729 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010730 // If we're defining a specialization and the previous definition
10731 // is from an implicit instantiation, don't emit an error
10732 // here; we'll catch this in the general case below.
Richard Smith1af83c42012-03-23 03:33:32 +000010733 bool IsExplicitSpecializationAfterInstantiation = false;
10734 if (isExplicitSpecialization) {
10735 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10736 IsExplicitSpecializationAfterInstantiation =
10737 RD->getTemplateSpecializationKind() !=
10738 TSK_ExplicitSpecialization;
10739 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10740 IsExplicitSpecializationAfterInstantiation =
10741 ED->getTemplateSpecializationKind() !=
10742 TSK_ExplicitSpecialization;
10743 }
10744
10745 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy16f1f712012-02-29 10:24:19 +000010746 // A redeclaration in function prototype scope in C isn't
10747 // visible elsewhere, so merely issue a warning.
David Blaikie4e4d0842012-03-11 07:00:24 +000010748 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy16f1f712012-02-29 10:24:19 +000010749 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10750 else
10751 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010752 Diag(Def->getLocation(), diag::note_previous_definition);
10753 // If this is a redefinition, recover by making this
10754 // struct be anonymous, which will make any later
10755 // references get the previous definition.
10756 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010757 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010758 Invalid = true;
10759 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010760 } else {
10761 // If the type is currently being defined, complain
10762 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +000010763 const TagType *Tag
10764 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010765 if (Tag->isBeingDefined()) {
10766 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +000010767 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010768 diag::note_previous_definition);
10769 Name = 0;
John McCall68263142009-11-18 22:49:29 +000010770 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010771 Invalid = true;
10772 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010773 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010774
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010775 // Okay, this is definition of a previously declared or referenced
10776 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010777 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010778 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010779 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +000010780 // have a definition. Just create a new decl.
10781
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010782 } else {
10783 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +000010784 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010785 // new decl/type. We set PrevDecl to NULL so that the entities
10786 // have distinct types.
John McCall68263142009-11-18 22:49:29 +000010787 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010788 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010789 // If we get here, we're going to create a new Decl. If PrevDecl
10790 // is non-NULL, it's a definition of the tag declared by
10791 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +000010792
10793
10794 // Otherwise, PrevDecl is not a tag, but was found with tag
10795 // lookup. This is only actually possible in C++, where a few
10796 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000010797 } else {
John McCall0d6b1642010-04-23 18:46:30 +000010798 // Use a better diagnostic if an elaborated-type-specifier
10799 // found the wrong kind of type on the first
10800 // (non-redeclaration) lookup.
10801 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10802 !Previous.isForRedeclaration()) {
10803 unsigned Kind = 0;
10804 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010805 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10806 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010807 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10808 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10809 Invalid = true;
10810
10811 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregorcc209452011-03-07 16:54:27 +000010812 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10813 isExplicitSpecialization)) {
John McCall0d6b1642010-04-23 18:46:30 +000010814 // do nothing
10815
10816 // Diagnose implicit declarations introduced by elaborated types.
10817 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10818 unsigned Kind = 0;
10819 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smith162e1c12011-04-15 14:24:37 +000010820 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10821 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCall0d6b1642010-04-23 18:46:30 +000010822 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10823 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10824 Invalid = true;
10825
10826 // Otherwise it's a declaration. Call out a particularly common
10827 // case here.
Richard Smith162e1c12011-04-15 14:24:37 +000010828 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10829 unsigned Kind = 0;
10830 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCall0d6b1642010-04-23 18:46:30 +000010831 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smith162e1c12011-04-15 14:24:37 +000010832 << Name << Kind << TND->getUnderlyingType();
John McCall0d6b1642010-04-23 18:46:30 +000010833 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10834 Invalid = true;
10835
10836 // Otherwise, diagnose.
10837 } else {
10838 // The tag name clashes with something else in the target scope,
10839 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +000010840 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +000010841 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010842 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010843 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +000010844 }
John McCall0d6b1642010-04-23 18:46:30 +000010845
10846 // The existing declaration isn't relevant to us; we're in a
10847 // new scope, so clear out the previous declaration.
10848 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +000010849 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010850 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000010851
Chris Lattnercc98eac2008-12-17 07:13:27 +000010852CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +000010853
John McCall68263142009-11-18 22:49:29 +000010854 TagDecl *PrevDecl = 0;
10855 if (Previous.isSingleResult())
10856 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10857
Reid Spencer5f016e22007-07-11 17:01:13 +000010858 // If there is an identifier, use the location of the identifier as the
10859 // location of the decl, otherwise use the location of the struct/union
10860 // keyword.
10861 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000010862
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010863 // Otherwise, create a new declaration. If there is a previous
10864 // declaration of the same entity, the two will be linked via
10865 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +000010866 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +000010867
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010868 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +000010869 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +000010870 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10871 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010872 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010873 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +000010874 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +000010875 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010876 if (TUK != TUK_Definition && !Invalid) {
10877 TagDecl *Def;
Douglas Gregorabde2c72013-03-25 22:22:35 +000010878 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10879 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010880 // C++0x: 7.2p2: opaque-enum-declaration.
10881 // Conflicts are diagnosed above. Do nothing.
10882 }
10883 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010884 Diag(Loc, diag::ext_forward_ref_enum_def)
10885 << New;
10886 Diag(Def->getLocation(), diag::note_previous_definition);
10887 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010888 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010889 if (getLangOpts().MicrosoftMode)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010890 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikie4e4d0842012-03-11 07:00:24 +000010891 else if (getLangOpts().CPlusPlus)
Francois Pichet8dc3abc2010-09-12 05:06:55 +000010892 DiagID = diag::err_forward_ref_enum;
10893 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010894
10895 // If this is a forward-declared reference to an enumeration, make a
10896 // note of it; we won't actually be introducing the declaration into
10897 // the declaration context.
10898 if (TUK == TUK_Reference)
10899 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +000010900 }
Douglas Gregor80711a22009-03-06 18:34:03 +000010901 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +000010902
10903 if (EnumUnderlying) {
10904 EnumDecl *ED = cast<EnumDecl>(New);
10905 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10906 ED->setIntegerTypeSourceInfo(TI);
10907 else
10908 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10909 ED->setPromotionType(ED->getIntegerType());
10910 }
10911
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000010912 } else {
10913 // struct/union/class
10914
Reid Spencer5f016e22007-07-11 17:01:13 +000010915 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10916 // struct X { int A; } D; D should chain to X.
David Blaikie4e4d0842012-03-11 07:00:24 +000010917 if (getLangOpts().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +000010918 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010919 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010920 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010921
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +000010922 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +000010923 StdBadAlloc = cast<CXXRecordDecl>(New);
10924 } else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000010925 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010926 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000010927 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010928
John McCallb6217662010-03-15 10:12:16 +000010929 // Maybe add qualifier info.
10930 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010931 if (SS.isSet()) {
Douglas Gregor69605872012-03-28 16:01:27 +000010932 // If this is either a declaration or a definition, check the
10933 // nested-name-specifier against the current context. We don't do this
10934 // for explicit specializations, because they have similar checking
10935 // (with more specific diagnostics) in the call to
10936 // CheckMemberSpecialization, below.
10937 if (!isExplicitSpecialization &&
10938 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10939 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10940 Invalid = true;
10941
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000010942 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010943 if (TemplateParameterLists.size() > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +000010944 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010945 TemplateParameterLists.size(),
Benjamin Kramer5354e772012-08-23 23:38:35 +000010946 TemplateParameterLists.data());
Abramo Bagnara9b934882010-06-12 08:15:14 +000010947 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +000010948 }
10949 else
10950 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +000010951 }
10952
Daniel Dunbar9f21f892010-05-27 01:53:40 +000010953 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10954 // Add alignment attributes if necessary; these attributes are checked when
10955 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010956 //
10957 // It is important for implementing the correct semantics that this
10958 // happen here (in act on tag decl). The #pragma pack stack is
10959 // maintained as a result of parser callbacks which can occur at
10960 // many points during the parsing of a struct declaration (because
10961 // the #pragma tokens are effectively skipped over during the
10962 // parsing of the struct).
Eli Friedman2016c8c2012-08-08 21:08:34 +000010963 if (TUK == TUK_Definition) {
10964 AddAlignmentAttributesForRecord(RD);
10965 AddMsStructLayoutForRecord(RD);
10966 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010967 }
10968
Douglas Gregor2ccd89c2011-12-20 18:11:52 +000010969 if (ModulePrivateLoc.isValid()) {
Douglas Gregord023aec2011-09-09 20:53:38 +000010970 if (isExplicitSpecialization)
10971 Diag(New->getLocation(), diag::err_module_private_specialization)
10972 << 2
10973 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregore3895852011-09-12 18:37:38 +000010974 // __module_private__ does not apply to local classes. However, we only
10975 // diagnose this as an error when the declaration specifiers are
10976 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregore3895852011-09-12 18:37:38 +000010977 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregore7612302011-09-09 19:05:14 +000010978 New->setModulePrivate();
10979 }
10980
Douglas Gregorf6b11852009-10-08 15:14:33 +000010981 // If this is a specialization of a member class (of a class template),
10982 // check the specialization.
John McCall68263142009-11-18 22:49:29 +000010983 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +000010984 Invalid = true;
Douglas Gregor69605872012-03-28 16:01:27 +000010985
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010986 if (Invalid)
10987 New->setInvalidDecl();
10988
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010989 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010990 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010991
Douglas Gregor0b7a1582009-01-17 00:42:38 +000010992 // If we're declaring or defining a tag in function prototype scope
10993 // in C, note that this type can only be used within the function.
David Blaikie4e4d0842012-03-11 07:00:24 +000010994 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor3218c4b2009-01-09 22:42:13 +000010995 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
10996
Douglas Gregor7df7b6b2008-12-15 16:32:14 +000010997 // Set the lexical context. If the tag has a C++ scope specifier, the
10998 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +000010999 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011000
John McCall02cace72009-08-28 07:59:38 +000011001 // Mark this as a friend decl if applicable.
Francois Pichetb4746032011-06-01 04:14:20 +000011002 // In Microsoft mode, a friend declaration also acts as a forward
11003 // declaration so we always pass true to setObjectOfFriendDecl to make
11004 // the tag name visible.
John McCall02cace72009-08-28 07:59:38 +000011005 if (TUK == TUK_Friend)
Richard Smith22050f22013-07-17 23:53:16 +000011006 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11007 getLangOpts().MicrosoftExt);
John McCall02cace72009-08-28 07:59:38 +000011008
Anders Carlsson0cf88302009-03-26 01:19:02 +000011009 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +000011010 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +000011011 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +000011012
John McCall0f434ec2009-07-31 02:45:11 +000011013 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +000011014 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +000011015
Reid Spencer5f016e22007-07-11 17:01:13 +000011016 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +000011017 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +000011018 // We might be replacing an existing declaration in the lookup tables;
11019 // if so, borrow its access specifier.
11020 if (PrevDecl)
11021 New->setAccess(PrevDecl->getAccess());
11022
Sebastian Redl7a126a42010-08-31 00:36:30 +000011023 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011024 DC->makeDeclVisibleInContext(New);
John McCall9c86b512010-03-25 21:28:06 +000011025 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +000011026 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11027 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +000011028 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000011029 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011030 PushOnScopeChains(New, S, !IsForwardReference);
11031 if (IsForwardReference)
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011032 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000011033
Douglas Gregor4920f1f2009-01-12 22:49:06 +000011034 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011035 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +000011036 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000011037
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011038 // If this is the C FILE type, notify the AST context.
11039 if (IdentifierInfo *II = New->getIdentifier())
11040 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +000011041 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +000011042 II->isStr("FILE"))
11043 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +000011044
James Molloy16f1f712012-02-29 10:24:19 +000011045 // If we were in function prototype scope (and not in C++ mode), add this
11046 // tag to the list of decls to inject into the function definition scope.
David Blaikie4e4d0842012-03-11 07:00:24 +000011047 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy16f1f712012-02-29 10:24:19 +000011048 InFunctionDeclarator && Name)
11049 DeclsInPrototypeScope.push_back(New);
11050
Rafael Espindola98ae8342012-05-10 02:50:16 +000011051 if (PrevDecl)
11052 mergeDeclAttributes(New, PrevDecl);
11053
Rafael Espindola71adc5b2012-07-17 15:14:47 +000011054 // If there's a #pragma GCC visibility in scope, set the visibility of this
11055 // record.
11056 AddPushedVisibilityAttribute(New);
11057
Douglas Gregor402abb52009-05-28 23:31:59 +000011058 OwnedDecl = true;
Richard Smith37ec8d52012-12-05 11:34:06 +000011059 // In C++, don't return an invalid declaration. We can't recover well from
11060 // the cases where we make the type anonymous.
11061 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Reid Spencer5f016e22007-07-11 17:01:13 +000011062}
11063
John McCalld226f652010-08-21 09:40:31 +000011064void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011065 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011066 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +000011067
Douglas Gregor72de6672009-01-08 20:45:30 +000011068 // Enter the tag context.
11069 PushDeclContext(S, Tag);
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000011070
11071 ActOnDocumentableDecl(TagD);
Rafael Espindola5e065292012-07-12 04:47:34 +000011072
11073 // If there's a #pragma GCC visibility in scope, set the visibility of this
11074 // record.
11075 AddPushedVisibilityAttribute(Tag);
John McCallf9368152009-12-20 07:58:13 +000011076}
Douglas Gregor72de6672009-01-08 20:45:30 +000011077
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011078Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011079 assert(isa<ObjCContainerDecl>(IDecl) &&
11080 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11081 DeclContext *OCD = cast<DeclContext>(IDecl);
11082 assert(getContainingDC(OCD) == CurContext &&
11083 "The next DeclContext should be lexically contained in the current one.");
11084 CurContext = OCD;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011085 return IDecl;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011086}
11087
John McCalld226f652010-08-21 09:40:31 +000011088void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011089 SourceLocation FinalLoc,
David Majnemer7121bdb2013-10-18 00:33:31 +000011090 bool IsFinalSpelledSealed,
John McCallf9368152009-12-20 07:58:13 +000011091 SourceLocation LBraceLoc) {
11092 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011093 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +000011094
John McCallf9368152009-12-20 07:58:13 +000011095 FieldCollector->StartClass();
11096
11097 if (!Record->getIdentifier())
11098 return;
11099
Anders Carlsson2c3ee542011-03-25 14:31:08 +000011100 if (FinalLoc.isValid())
David Majnemer7121bdb2013-10-18 00:33:31 +000011101 Record->addAttr(new (Context)
11102 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11103
John McCallf9368152009-12-20 07:58:13 +000011104 // C++ [class]p2:
11105 // [...] The class-name is also inserted into the scope of the
11106 // class itself; this is known as the injected-class-name. For
11107 // purposes of access checking, the injected-class-name is treated
11108 // as if it were a public member name.
11109 CXXRecordDecl *InjectedClassName
Abramo Bagnaraba877ad2011-03-09 14:09:51 +000011110 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11111 Record->getLocStart(), Record->getLocation(),
John McCallf9368152009-12-20 07:58:13 +000011112 Record->getIdentifier(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +000011113 /*PrevDecl=*/0,
11114 /*DelayTypeCreation=*/true);
11115 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +000011116 InjectedClassName->setImplicit();
11117 InjectedClassName->setAccess(AS_public);
11118 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11119 InjectedClassName->setDescribedClassTemplate(Template);
11120 PushOnScopeChains(InjectedClassName, S);
11121 assert(InjectedClassName->isInjectedClassName() &&
11122 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +000011123}
11124
John McCalld226f652010-08-21 09:40:31 +000011125void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011126 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +000011127 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011128 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +000011129 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +000011130
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011131 // Make sure we "complete" the definition even it is invalid.
11132 if (Tag->isBeingDefined()) {
11133 assert(Tag->isInvalidDecl() && "We should already have completed it");
11134 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11135 RD->completeDefinition();
11136 }
11137
Douglas Gregor72de6672009-01-08 20:45:30 +000011138 if (isa<CXXRecordDecl>(Tag))
11139 FieldCollector->FinishClass();
11140
11141 // Exit this scope of this tag's definition.
11142 PopDeclContext();
Argyrios Kyrtzidis3d207e72013-01-29 18:00:54 +000011143
11144 if (getCurLexicalContext()->isObjCContainer() &&
11145 Tag->getDeclContext()->isFileContext())
11146 Tag->setTopLevelDeclInObjCContainer();
11147
Douglas Gregor72de6672009-01-08 20:45:30 +000011148 // Notify the consumer that we've defined a tag.
Serge Pavlov439b7012013-07-02 17:31:56 +000011149 if (!Tag->isInvalidDecl())
11150 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor72de6672009-01-08 20:45:30 +000011151}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +000011152
Fariborz Jahanian10af8792011-08-29 17:33:12 +000011153void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011154 // Exit this scope of this interface definition.
11155 PopDeclContext();
11156}
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011157
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011158void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis4a7dc8a2011-10-27 00:53:06 +000011159 assert(DC == CurContext && "Mismatch of container contexts");
11160 OriginalLexicalContext = DC;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011161 ActOnObjCContainerFinishDefinition();
11162}
11163
Argyrios Kyrtzidis458bacf2011-10-27 00:09:34 +000011164void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11165 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +000011166 OriginalLexicalContext = 0;
11167}
11168
John McCalld226f652010-08-21 09:40:31 +000011169void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +000011170 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +000011171 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +000011172 Tag->setInvalidDecl();
11173
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011174 // Make sure we "complete" the definition even it is invalid.
11175 if (Tag->isBeingDefined()) {
11176 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11177 RD->completeDefinition();
11178 }
11179
John McCalla8cab012010-03-17 19:25:57 +000011180 // We're undoing ActOnTagStartDefinition here, not
11181 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11182 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +000011183
11184 PopDeclContext();
11185}
11186
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011187// Note that FieldName may be null for anonymous bitfields.
Richard Smith282e7e62012-02-04 09:53:13 +000011188ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11189 IdentifierInfo *FieldName,
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011190 QualType FieldTy, bool IsMsStruct,
11191 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedman1d954f62009-08-15 21:55:26 +000011192 // Default to true; that shouldn't confuse checks for emptiness
11193 if (ZeroWidth)
11194 *ZeroWidth = true;
11195
Chris Lattner24793662009-03-05 22:45:59 +000011196 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +000011197 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000011198 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +000011199 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +000011200 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smith282e7e62012-02-04 09:53:13 +000011201 return ExprError();
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011202 if (FieldName)
11203 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11204 << FieldName << FieldTy << BitWidth->getSourceRange();
11205 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11206 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +000011207 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11208 UPPC_BitFieldWidth))
Richard Smith282e7e62012-02-04 09:53:13 +000011209 return ExprError();
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011210
11211 // If the bit-width is type- or value-dependent, don't try to check
11212 // it now.
11213 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smith282e7e62012-02-04 09:53:13 +000011214 return Owned(BitWidth);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011215
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011216 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +000011217 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11218 if (ICE.isInvalid())
11219 return ICE;
11220 BitWidth = ICE.take();
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011221
Eli Friedman1d954f62009-08-15 21:55:26 +000011222 if (Value != 0 && ZeroWidth)
11223 *ZeroWidth = false;
11224
Chris Lattnercd087072008-12-12 04:56:04 +000011225 // Zero-width bitfield is ok for anonymous field.
11226 if (Value == 0 && FieldName)
11227 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +000011228
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011229 if (Value.isSigned() && Value.isNegative()) {
11230 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +000011231 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011232 << FieldName << Value.toString(10);
11233 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11234 << Value.toString(10);
11235 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011236
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011237 if (!FieldTy->isDependentType()) {
11238 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011239 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011240 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlsson72468ec2010-04-16 15:16:32 +000011241 if (FieldName)
11242 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11243 << FieldName << (unsigned)Value.getZExtValue()
11244 << (unsigned)TypeSize;
11245
11246 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11247 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11248 }
11249
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011250 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +000011251 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11252 << FieldName << (unsigned)Value.getZExtValue()
11253 << (unsigned)TypeSize;
11254 else
11255 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11256 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +000011257 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011258 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011259
Richard Smith282e7e62012-02-04 09:53:13 +000011260 return Owned(BitWidth);
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011261}
11262
Richard Smith7a614d82011-06-11 17:19:42 +000011263/// ActOnField - Each field of a C struct/union is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +000011264/// to create a FieldDecl object for it.
Richard Smith7a614d82011-06-11 17:19:42 +000011265Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011266 Declarator &D, Expr *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +000011267 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +000011268 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smithca523302012-06-10 03:12:00 +000011269 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCalld226f652010-08-21 09:40:31 +000011270 return Res;
Chris Lattner24793662009-03-05 22:45:59 +000011271}
11272
11273/// HandleField - Analyze a field of a C struct or a C++ data member.
11274///
11275FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11276 SourceLocation DeclStart,
Richard Smithca523302012-06-10 03:12:00 +000011277 Declarator &D, Expr *BitWidth,
11278 InClassInitStyle InitStyle,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011279 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011280 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +000011281 SourceLocation Loc = DeclStart;
11282 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011283
John McCallbf1a0282010-06-04 23:28:52 +000011284 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11285 QualType T = TInfo->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +000011286 if (getLangOpts().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011287 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +000011288
Douglas Gregore1862692010-12-15 23:18:36 +000011289 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11290 UPPC_DataMemberType)) {
11291 D.setInvalidType();
11292 T = Context.IntTy;
11293 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11294 }
11295 }
11296
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011297 // TR 18037 does not allow fields to be declared with address spaces.
11298 if (T.getQualifiers().hasAddressSpace()) {
11299 Diag(Loc, diag::err_field_with_address_space);
11300 D.setInvalidType();
11301 }
11302
Guy Benyeie6b9d802013-01-20 12:31:11 +000011303 // OpenCL 1.2 spec, s6.9 r:
11304 // The event type cannot be used to declare a structure or union field.
11305 if (LangOpts.OpenCL && T->isEventT()) {
11306 Diag(Loc, diag::err_event_t_struct_field);
11307 D.setInvalidType();
11308 }
11309
Richard Smithc7f81162013-03-18 22:52:47 +000011310 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman85a53192009-04-07 19:37:57 +000011311
Richard Smithec642442013-04-12 22:46:28 +000011312 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11313 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11314 diag::err_invalid_thread)
11315 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault34b0adb2013-02-26 21:16:00 +000011316
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011317 // Check to see if this name was declared as a member previously
Douglas Gregor95e55102011-10-21 15:47:52 +000011318 NamedDecl *PrevDecl = 0;
Douglas Gregor7f6ff022010-08-30 14:32:14 +000011319 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11320 LookupName(Previous, S);
Douglas Gregor95e55102011-10-21 15:47:52 +000011321 switch (Previous.getResultKind()) {
11322 case LookupResult::Found:
11323 case LookupResult::FoundUnresolvedValue:
11324 PrevDecl = Previous.getAsSingle<NamedDecl>();
11325 break;
11326
11327 case LookupResult::FoundOverloaded:
11328 PrevDecl = Previous.getRepresentativeDecl();
11329 break;
11330
11331 case LookupResult::NotFound:
11332 case LookupResult::NotFoundInCurrentInstantiation:
11333 case LookupResult::Ambiguous:
11334 break;
11335 }
11336 Previous.suppressDiagnostics();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +000011337
11338 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11339 // Maybe we will complain about the shadowed template parameter.
11340 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11341 // Just pretend that we didn't see the previous declaration.
11342 PrevDecl = 0;
11343 }
11344
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011345 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11346 PrevDecl = 0;
11347
Steve Naroffea218b82009-07-14 14:58:18 +000011348 bool Mutable
11349 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar96a00142012-03-09 18:35:03 +000011350 SourceLocation TSSL = D.getLocStart();
Steve Naroffea218b82009-07-14 14:58:18 +000011351 FieldDecl *NewFD
Richard Smithca523302012-06-10 03:12:00 +000011352 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith7a614d82011-06-11 17:19:42 +000011353 TSSL, AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +000011354
11355 if (NewFD->isInvalidDecl())
11356 Record->setInvalidDecl();
11357
Douglas Gregor591dc842011-09-12 16:11:24 +000011358 if (D.getDeclSpec().isModulePrivateSpecified())
11359 NewFD->setModulePrivate();
11360
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011361 if (NewFD->isInvalidDecl() && PrevDecl) {
11362 // Don't introduce NewFD into scope; there's already something
11363 // with the same name in the same scope.
11364 } else if (II) {
11365 PushOnScopeChains(NewFD, S);
11366 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011367 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011368
11369 return NewFD;
11370}
11371
11372/// \brief Build a new FieldDecl and check its well-formedness.
11373///
11374/// This routine builds a new FieldDecl given the fields name, type,
11375/// record, etc. \p PrevDecl should refer to any previous declaration
11376/// with the same name and in the same scope as the field to be
11377/// created.
11378///
11379/// \returns a new FieldDecl.
11380///
Mike Stump1eb44332009-09-09 15:08:12 +000011381/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +000011382FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +000011383 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011384 RecordDecl *Record, SourceLocation Loc,
Richard Smithca523302012-06-10 03:12:00 +000011385 bool Mutable, Expr *BitWidth,
11386 InClassInitStyle InitStyle,
Steve Naroffea218b82009-07-14 14:58:18 +000011387 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011388 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011389 Declarator *D) {
11390 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +000011391 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +000011392 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +000011393
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011394 // If we receive a broken type, recover by assuming 'int' and
11395 // marking this declaration as invalid.
11396 if (T.isNull()) {
11397 InvalidDecl = true;
11398 T = Context.IntTy;
11399 }
11400
Eli Friedman721e77d2009-12-07 00:22:08 +000011401 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis216f78b2012-03-09 20:10:30 +000011402 if (!EltTy->isDependentType()) {
11403 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11404 // Fields of incomplete type force their record to be invalid.
11405 Record->setInvalidDecl();
11406 InvalidDecl = true;
11407 } else {
11408 NamedDecl *Def;
11409 EltTy->isIncompleteType(&Def);
11410 if (Def && Def->isInvalidDecl()) {
11411 Record->setInvalidDecl();
11412 InvalidDecl = true;
11413 }
11414 }
John McCall2d7d2d92010-08-16 23:42:35 +000011415 }
Eli Friedman721e77d2009-12-07 00:22:08 +000011416
Joey Gouly617bb312013-01-17 17:35:00 +000011417 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11418 if (BitWidth && getLangOpts().OpenCL) {
11419 Diag(Loc, diag::err_opencl_bitfields);
11420 InvalidDecl = true;
11421 }
11422
Reid Spencer5f016e22007-07-11 17:01:13 +000011423 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11424 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +000011425 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011426 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +000011427 llvm::APSInt Oversized;
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011428
11429 TypeSourceInfo *FixedTInfo =
11430 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11431 SizeIsNegative,
11432 Oversized);
11433 if (FixedTInfo) {
Eli Friedman1ca48132009-02-21 00:44:51 +000011434 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara4c5750e2012-11-08 14:44:42 +000011435 TInfo = FixedTInfo;
11436 T = FixedTInfo->getType();
Eli Friedman1ca48132009-02-21 00:44:51 +000011437 } else {
11438 if (SizeIsNegative)
11439 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +000011440 else if (Oversized.getBoolValue())
11441 Diag(Loc, diag::err_array_too_large)
11442 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +000011443 else
11444 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +000011445 InvalidDecl = true;
11446 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011447 }
Mike Stump1eb44332009-09-09 15:08:12 +000011448
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011449 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +000011450 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11451 diag::err_abstract_type_in_decl,
11452 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +000011453 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +000011454
Eli Friedman1d954f62009-08-15 21:55:26 +000011455 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011456 // If this is declared as a bit-field, check the bit-field.
Richard Smith282e7e62012-02-04 09:53:13 +000011457 if (!InvalidDecl && BitWidth) {
Reid Kleckner9a3ecb02013-07-17 20:46:03 +000011458 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11459 &ZeroWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011460 if (!BitWidth) {
11461 InvalidDecl = true;
11462 BitWidth = 0;
11463 ZeroWidth = false;
11464 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +000011465 }
Mike Stump1eb44332009-09-09 15:08:12 +000011466
John McCall4bde1e12010-06-04 08:34:12 +000011467 // Check that 'mutable' is consistent with the type of the declaration.
11468 if (!InvalidDecl && Mutable) {
11469 unsigned DiagID = 0;
11470 if (T->isReferenceType())
11471 DiagID = diag::err_mutable_reference;
11472 else if (T.isConstQualified())
11473 DiagID = diag::err_mutable_const;
11474
11475 if (DiagID) {
11476 SourceLocation ErrLoc = Loc;
11477 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11478 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11479 Diag(ErrLoc, DiagID);
11480 Mutable = false;
11481 InvalidDecl = true;
11482 }
11483 }
11484
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011485 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +000011486 BitWidth, Mutable, InitStyle);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011487 if (InvalidDecl)
11488 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +000011489
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011490 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11491 Diag(Loc, diag::err_duplicate_member) << II;
11492 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11493 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +000011494 }
11495
David Blaikie4e4d0842012-03-11 07:00:24 +000011496 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +000011497 if (Record->isUnion()) {
11498 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11499 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11500 if (RDecl->getDefinition()) {
11501 // C++ [class.union]p1: An object of a class with a non-trivial
11502 // constructor, a non-trivial copy constructor, a non-trivial
11503 // destructor, or a non-trivial copy assignment operator
11504 // cannot be a member of a union, nor can an array of such
11505 // objects.
Richard Smithe7d7c392011-10-19 20:41:51 +000011506 if (CheckNontrivialField(NewFD))
Anders Carlssondfdfc582010-11-07 19:13:55 +000011507 NewFD->setInvalidDecl();
11508 }
11509 }
11510
11511 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballman76eed422013-05-30 16:20:00 +000011512 // the program is ill-formed, except when compiling with MSVC extensions
11513 // enabled.
Anders Carlssondfdfc582010-11-07 19:13:55 +000011514 if (EltTy->isReferenceType()) {
Aaron Ballman76eed422013-05-30 16:20:00 +000011515 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11516 diag::ext_union_member_of_reference_type :
11517 diag::err_union_member_of_reference_type)
Anders Carlssondfdfc582010-11-07 19:13:55 +000011518 << NewFD->getDeclName() << EltTy;
Aaron Ballman76eed422013-05-30 16:20:00 +000011519 if (!getLangOpts().MicrosoftExt)
11520 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +000011521 }
11522 }
11523 }
11524
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011525 // FIXME: We need to pass in the attributes given an AST
11526 // representation, not a parser representation.
Richard Smithbe507b62013-02-01 08:12:08 +000011527 if (D) {
Douglas Gregor92eb7d82013-05-02 23:25:32 +000011528 // FIXME: The current scope is almost... but not entirely... correct here.
11529 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +000011530
Richard Smithbe507b62013-02-01 08:12:08 +000011531 if (NewFD->hasAttrs())
11532 CheckAlignasUnderalignment(NewFD);
11533 }
11534
John McCallf85e1932011-06-15 23:02:42 +000011535 // In auto-retain/release, infer strong retension for fields of
11536 // retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011537 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCallf85e1932011-06-15 23:02:42 +000011538 NewFD->setInvalidDecl();
11539
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +000011540 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +000011541 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +000011542
Douglas Gregor4dd55f52009-03-11 20:50:30 +000011543 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +000011544 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +000011545}
11546
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011547bool Sema::CheckNontrivialField(FieldDecl *FD) {
11548 assert(FD);
David Blaikie4e4d0842012-03-11 07:00:24 +000011549 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011550
Nick Lewyckydccd04d2013-06-25 23:22:23 +000011551 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11552 return false;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011553
11554 QualType EltTy = Context.getBaseElementType(FD->getType());
11555 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smithac713512012-12-08 02:53:02 +000011556 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011557 if (RDecl->getDefinition()) {
11558 // We check for copy constructors before constructors
11559 // because otherwise we'll never get complaints about
11560 // copy constructors.
11561
11562 CXXSpecialMember member = CXXInvalid;
Richard Smith426391c2012-11-16 00:53:38 +000011563 // We're required to check for any non-trivial constructors. Since the
11564 // implicit default constructor is suppressed if there are any
11565 // user-declared constructors, we just need to check that there is a
11566 // trivial default constructor and a trivial copy constructor. (We don't
11567 // worry about move constructors here, since this is a C++98 check.)
11568 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011569 member = CXXCopyConstructor;
Sean Hunt023df372011-05-09 18:22:59 +000011570 else if (!RDecl->hasTrivialDefaultConstructor())
Sean Huntf961ea52011-05-10 19:08:14 +000011571 member = CXXDefaultConstructor;
Richard Smith426391c2012-11-16 00:53:38 +000011572 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011573 member = CXXCopyAssignment;
Richard Smith426391c2012-11-16 00:53:38 +000011574 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011575 member = CXXDestructor;
11576
11577 if (member != CXXInvalid) {
Richard Smith80ad52f2013-01-02 11:42:31 +000011578 if (!getLangOpts().CPlusPlus11 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011579 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCallf85e1932011-06-15 23:02:42 +000011580 // Objective-C++ ARC: it is an error to have a non-trivial field of
11581 // a union. However, system headers in Objective-C programs
11582 // occasionally have Objective-C lifetime objects within unions,
11583 // and rather than cause the program to fail, we make those
11584 // members unavailable.
11585 SourceLocation Loc = FD->getLocation();
11586 if (getSourceManager().isInSystemHeader(Loc)) {
11587 if (!FD->hasAttr<UnavailableAttr>())
11588 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011589 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011590 return false;
11591 }
11592 }
Richard Smithe7d7c392011-10-19 20:41:51 +000011593
Richard Smith80ad52f2013-01-02 11:42:31 +000011594 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithe7d7c392011-10-19 20:41:51 +000011595 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11596 diag::err_illegal_union_or_anon_struct_member)
11597 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smithac713512012-12-08 02:53:02 +000011598 DiagnoseNontrivial(RDecl, member);
Richard Smith80ad52f2013-01-02 11:42:31 +000011599 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011600 }
11601 }
11602 }
Richard Smithac713512012-12-08 02:53:02 +000011603
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +000011604 return false;
11605}
11606
Mike Stump1eb44332009-09-09 15:08:12 +000011607/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011608/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000011609static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +000011610TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +000011611 switch (ivarVisibility) {
David Blaikieb219cfc2011-09-23 05:06:16 +000011612 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner33d34a62008-10-12 00:28:42 +000011613 case tok::objc_private: return ObjCIvarDecl::Private;
11614 case tok::objc_public: return ObjCIvarDecl::Public;
11615 case tok::objc_protected: return ObjCIvarDecl::Protected;
11616 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +000011617 }
11618}
11619
Mike Stump1eb44332009-09-09 15:08:12 +000011620/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +000011621/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +000011622Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +000011623 SourceLocation DeclStart,
Richard Trieuf81e5a92011-09-09 02:00:50 +000011624 Declarator &D, Expr *BitfieldWidth,
Chris Lattnerb28317a2009-03-28 19:18:32 +000011625 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +000011626
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011627 IdentifierInfo *II = D.getIdentifier();
11628 Expr *BitWidth = (Expr*)BitfieldWidth;
11629 SourceLocation Loc = DeclStart;
11630 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +000011631
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011632 // FIXME: Unnamed fields can be handled in various different ways, for
11633 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +000011634
John McCallbf1a0282010-06-04 23:28:52 +000011635 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11636 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000011637
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011638 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +000011639 // 6.7.2.1p3, 6.7.2.1p4
Warren Huntb2969b12013-10-11 20:19:00 +000011640 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smith282e7e62012-02-04 09:53:13 +000011641 if (!BitWidth)
Chris Lattnereaaebc72009-04-25 08:06:05 +000011642 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011643 } else {
11644 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +000011645
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011646 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +000011647
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011648 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011649 if (T->isReferenceType()) {
11650 Diag(Loc, diag::err_ivar_reference_type);
11651 D.setInvalidType();
11652 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011653 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11654 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +000011655 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +000011656 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +000011657 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011658 }
Mike Stump1eb44332009-09-09 15:08:12 +000011659
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011660 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +000011661 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011662 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11663 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011664 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011665 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanianc645ddf2012-02-02 00:49:12 +000011666 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11667 return 0;
Daniel Dunbara19331f2010-04-02 18:29:09 +000011668 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +000011669 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011670 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011671 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011672 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +000011673 EnclosingContext = IMPDecl->getClassInterface();
11674 assert(EnclosingContext && "Implementation has no class interface!");
11675 }
11676 else
11677 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011678 } else {
11679 if (ObjCCategoryDecl *CDecl =
11680 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall260611a2012-06-20 06:18:46 +000011681 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011682 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +000011683 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011684 }
11685 }
Daniel Dunbara19331f2010-04-02 18:29:09 +000011686 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000011687 }
Mike Stump1eb44332009-09-09 15:08:12 +000011688
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011689 // Construct the decl.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011690 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11691 DeclStart, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +000011692 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +000011693
Douglas Gregor72de6672009-01-08 20:45:30 +000011694 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000011695 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +000011696 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000011697 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +000011698 && !isa<TagDecl>(PrevDecl)) {
11699 Diag(Loc, diag::err_duplicate_member) << II;
11700 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11701 NewID->setInvalidDecl();
11702 }
11703 }
11704
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011705 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011706 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +000011707
Chris Lattnereaaebc72009-04-25 08:06:05 +000011708 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011709 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +000011710
John McCallf85e1932011-06-15 23:02:42 +000011711 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011712 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCallf85e1932011-06-15 23:02:42 +000011713 NewID->setInvalidDecl();
11714
Douglas Gregor591dc842011-09-12 16:11:24 +000011715 if (D.getDeclSpec().isModulePrivateSpecified())
11716 NewID->setModulePrivate();
11717
Douglas Gregor72de6672009-01-08 20:45:30 +000011718 if (II) {
11719 // FIXME: When interfaces are DeclContexts, we'll need to add
11720 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +000011721 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +000011722 IdResolver.AddDecl(NewID);
11723 }
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011724
John McCall260611a2012-06-20 06:18:46 +000011725 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011726 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniandc3eb6a2012-05-15 17:43:16 +000011727 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian8f674a82012-05-15 16:33:04 +000011728
John McCalld226f652010-08-21 09:40:31 +000011729 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +000011730}
11731
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011732/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosed4582b82013-04-03 01:39:23 +000011733/// class and class extensions. For every class \@interface and class
11734/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011735/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011736void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011737 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall260611a2012-06-20 06:18:46 +000011738 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011739 return;
11740
11741 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11742 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11743
Richard Smitha6b8b2c2011-10-10 18:28:20 +000011744 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011745 return;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011746 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011747 if (!ID) {
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011748 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011749 if (!CD->IsClassExtension())
11750 return;
11751 }
11752 // No need to add this to end of @implementation.
11753 else
11754 return;
11755 }
11756 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011757 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11758 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011759
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000011760 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011761 DeclLoc, DeclLoc, 0,
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011762 Context.CharTy,
Douglas Gregor0bbea1b2011-08-03 16:26:46 +000011763 Context.getTrivialTypeSourceInfo(Context.CharTy,
11764 DeclLoc),
Fariborz Jahaniand097be82010-08-23 22:46:52 +000011765 ObjCIvarDecl::Private, BW,
11766 true);
11767 AllIvarDecls.push_back(Ivar);
11768}
11769
Robert Wilhelm834c0582013-08-09 18:02:13 +000011770void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11771 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11772 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +000011773 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +000011774
Eric Christopher6dba4a12012-07-19 22:22:51 +000011775 // If this is an Objective-C @implementation or category and we have
11776 // new fields here we should reset the layout of the interface since
11777 // it will now change.
11778 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11779 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11780 switch (DC->getKind()) {
11781 default: break;
11782 case Decl::ObjCCategory:
11783 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11784 break;
11785 case Decl::ObjCImplementation:
11786 Context.
11787 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11788 break;
11789 }
11790 }
11791
Eli Friedman11e70d72012-02-07 05:00:47 +000011792 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11793
11794 // Start counting up the number of named members; make sure to include
11795 // members of anonymous structs and unions in the total.
Reid Spencer5f016e22007-07-11 17:01:13 +000011796 unsigned NumNamedMembers = 0;
Eli Friedman11e70d72012-02-07 05:00:47 +000011797 if (Record) {
11798 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11799 e = Record->decls_end(); i != e; i++) {
11800 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11801 if (IFD->getDeclName())
11802 ++NumNamedMembers;
11803 }
11804 }
11805
11806 // Verify that all the fields are okay.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011807 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011808
John McCallf85e1932011-06-15 23:02:42 +000011809 bool ARCErrReported = false;
Robert Wilhelm834c0582013-08-09 18:02:13 +000011810 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie77b6de02011-09-22 02:58:26 +000011811 i != end; ++i) {
11812 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump1eb44332009-09-09 15:08:12 +000011813
Reid Spencer5f016e22007-07-11 17:01:13 +000011814 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +000011815 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011816
Douglas Gregor72de6672009-01-08 20:45:30 +000011817 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +000011818 // Remember all fields written by the user.
11819 RecFields.push_back(FD);
11820 }
Mike Stump1eb44332009-09-09 15:08:12 +000011821
Chris Lattner24793662009-03-05 22:45:59 +000011822 // If the field is already invalid for some reason, don't emit more
11823 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +000011824 if (FD->isInvalidDecl()) {
11825 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +000011826 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +000011827 }
Mike Stump1eb44332009-09-09 15:08:12 +000011828
Douglas Gregore7450f52009-03-24 19:52:54 +000011829 // C99 6.7.2.1p2:
11830 // A structure or union shall not contain a member with
11831 // incomplete or function type (hence, a structure shall not
11832 // contain an instance of itself, but may contain a pointer to
11833 // an instance of itself), except that the last member of a
11834 // structure with more than one named member may have incomplete
11835 // array type; such a structure (and any union containing,
11836 // possibly recursively, a member that is such a structure)
11837 // shall not be a member of a structure or an element of an
11838 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +000011839 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011840 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011841 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011842 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +000011843 FD->setInvalidDecl();
11844 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +000011845 continue;
Francois Pichet09246182010-09-15 00:14:08 +000011846 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie77b6de02011-09-22 02:58:26 +000011847 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikie4e4d0842012-03-11 07:00:24 +000011848 ((getLangOpts().MicrosoftExt ||
11849 getLangOpts().CPlusPlus) &&
David Blaikie77b6de02011-09-22 02:58:26 +000011850 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011851 // Flexible array member.
Argyrios Kyrtzidisd97cec32011-03-07 20:04:04 +000011852 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichet09246182010-09-15 00:14:08 +000011853 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +000011854 // as the sole element of a struct/class.
David Majnemer633c0c22013-11-02 10:38:05 +000011855 unsigned DiagID = 0;
11856 if (Record->isUnion())
11857 DiagID = getLangOpts().MicrosoftExt
11858 ? diag::ext_flexible_array_union_ms
11859 : getLangOpts().CPlusPlus
11860 ? diag::ext_flexible_array_union_gnu
11861 : diag::err_flexible_array_union;
11862 else if (Fields.size() == 1)
11863 DiagID = getLangOpts().MicrosoftExt
11864 ? diag::ext_flexible_array_empty_aggregate_ms
11865 : getLangOpts().CPlusPlus
11866 ? diag::ext_flexible_array_empty_aggregate_gnu
11867 : NumNamedMembers < 1
11868 ? diag::err_flexible_array_empty_aggregate
11869 : 0;
11870
11871 if (DiagID)
11872 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11873 << Record->getTagKind();
David Majnemer3a665572013-11-02 11:19:13 +000011874 // While the layout of types that contain virtual bases is not specified
11875 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11876 // virtual bases after the derived members. This would make a flexible
11877 // array member declared at the end of an object not adjacent to the end
11878 // of the type.
11879 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11880 if (RD->getNumVBases() != 0)
11881 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11882 << FD->getDeclName() << Record->getTagKind();
David Majnemer633c0c22013-11-02 10:38:05 +000011883 if (!getLangOpts().C99)
11884 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11885 << FD->getDeclName() << Record->getTagKind();
11886
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011887 if (!FD->getType()->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +000011888 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011889 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +000011890 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000011891 FD->setInvalidDecl();
11892 EnclosingDecl->setInvalidDecl();
11893 continue;
11894 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011895 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +000011896 if (Record)
11897 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +000011898 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +000011899 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +000011900 diag::err_field_incomplete)) {
11901 // Incomplete type
11902 FD->setInvalidDecl();
11903 EnclosingDecl->setInvalidDecl();
11904 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +000011905 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011906 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11907 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +000011908 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +000011909 Record->setHasFlexibleArrayMember(true);
11910 } else {
11911 // If this is a struct/class and this is not the last element, reject
11912 // it. Note that GCC supports variable sized arrays in the middle of
11913 // structures.
David Blaikie77b6de02011-09-22 02:58:26 +000011914 if (i + 1 != Fields.end())
Douglas Gregore4f3e062009-03-06 23:41:27 +000011915 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +000011916 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +000011917 else {
11918 // We support flexible arrays at the end of structs in
11919 // other structs as an extension.
11920 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11921 << FD->getDeclName();
11922 if (Record)
11923 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011924 }
Reid Spencer5f016e22007-07-11 17:01:13 +000011925 }
11926 }
Fariborz Jahanian7f90b532012-08-16 22:38:41 +000011927 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11928 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11929 diag::err_abstract_type_in_decl,
11930 AbstractIvarType)) {
11931 // Ivars can not have abstract class types
11932 FD->setInvalidDecl();
11933 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000011934 if (Record && FDTTy->getDecl()->hasObjectMember())
11935 Record->setHasObjectMember(true);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011936 if (Record && FDTTy->getDecl()->hasVolatileMember())
11937 Record->setHasVolatileMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +000011938 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +000011939 /// A field cannot be an Objective-c object
Fariborz Jahanian8eaefdc2011-07-26 17:58:54 +000011940 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11941 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11942 QualType T = Context.getObjCObjectPointerType(FD->getType());
11943 FD->setType(T);
Douglas Gregor4581d452013-01-28 19:08:09 +000011944 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11945 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11946 // It's an error in ARC if a field has lifetime.
11947 // We don't want to report this in a system header, though,
11948 // so we just make the field unavailable.
11949 // FIXME: that's really not sufficient; we need to make the type
11950 // itself invalid to, say, initialize or copy.
11951 QualType T = FD->getType();
11952 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11953 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11954 SourceLocation loc = FD->getLocation();
11955 if (getSourceManager().isInSystemHeader(loc)) {
11956 if (!FD->hasAttr<UnavailableAttr>()) {
11957 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11958 "this system field has retaining ownership"));
John McCallf85e1932011-06-15 23:02:42 +000011959 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011960 } else {
11961 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregorbde67cf2013-01-28 20:13:44 +000011962 << T->isBlockPointerType() << Record->getTagKind();
John McCallf85e1932011-06-15 23:02:42 +000011963 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011964 ARCErrReported = true;
John McCallf85e1932011-06-15 23:02:42 +000011965 }
Douglas Gregor4581d452013-01-28 19:08:09 +000011966 } else if (getLangOpts().ObjC1 &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011967 getLangOpts().getGC() != LangOptions::NonGC &&
John McCallf85e1932011-06-15 23:02:42 +000011968 Record && !Record->hasObjectMember()) {
Douglas Gregor4581d452013-01-28 19:08:09 +000011969 if (FD->getType()->isObjCObjectPointerType() ||
11970 FD->getType().isObjCGCStrong())
11971 Record->setHasObjectMember(true);
11972 else if (Context.getAsArrayType(FD->getType())) {
11973 QualType BaseType = Context.getBaseElementType(FD->getType());
11974 if (BaseType->isRecordType() &&
11975 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCallf85e1932011-06-15 23:02:42 +000011976 Record->setHasObjectMember(true);
Douglas Gregor4581d452013-01-28 19:08:09 +000011977 else if (BaseType->isObjCObjectPointerType() ||
11978 BaseType.isObjCGCStrong())
11979 Record->setHasObjectMember(true);
John McCallf85e1932011-06-15 23:02:42 +000011980 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +000011981 }
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +000011982 if (Record && FD->getType().isVolatileQualified())
11983 Record->setHasVolatileMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +000011984 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +000011985 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +000011986 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +000011987 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000011988
Reid Spencer5f016e22007-07-11 17:01:13 +000011989 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +000011990 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011991 bool Completed = false;
11992 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
11993 if (!CXXRecord->isInvalidDecl()) {
11994 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011995 for (CXXRecordDecl::conversion_iterator
11996 I = CXXRecord->conversion_begin(),
11997 E = CXXRecord->conversion_end(); I != E; ++I)
11998 I.setAccess((*I)->getAccess());
Douglas Gregor7a39dd02010-09-29 00:15:42 +000011999
12000 if (!CXXRecord->isDependentType()) {
Peter Collingbournef51cfb82013-05-20 14:12:25 +000012001 if (CXXRecord->hasUserDeclaredDestructor()) {
12002 // Adjust user-defined destructor exception spec.
12003 if (getLangOpts().CPlusPlus11)
12004 AdjustDestructorExceptionSpec(CXXRecord,
12005 CXXRecord->getDestructor());
12006
12007 // The Microsoft ABI requires that we perform the destructor body
12008 // checks (i.e. operator delete() lookup) at every declaration, as
12009 // any translation unit may need to emit a deleting destructor.
12010 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12011 CheckDestructor(CXXRecord->getDestructor());
12012 }
Sebastian Redl0ee33912011-05-19 05:13:44 +000012013
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012014 // Add any implicitly-declared members to this class.
12015 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12016
12017 // If we have virtual base classes, we may end up finding multiple
12018 // final overriders for a given virtual function. Check for this
12019 // problem now.
12020 if (CXXRecord->getNumVBases()) {
12021 CXXFinalOverriderMap FinalOverriders;
12022 CXXRecord->getFinalOverriders(FinalOverriders);
12023
12024 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12025 MEnd = FinalOverriders.end();
12026 M != MEnd; ++M) {
12027 for (OverridingMethods::iterator SO = M->second.begin(),
12028 SOEnd = M->second.end();
12029 SO != SOEnd; ++SO) {
12030 assert(SO->second.size() > 0 &&
12031 "Virtual function without overridding functions?");
12032 if (SO->second.size() == 1)
12033 continue;
12034
12035 // C++ [class.virtual]p2:
12036 // In a derived class, if a virtual member function of a base
12037 // class subobject has more than one final overrider the
12038 // program is ill-formed.
12039 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divacky31ba6132012-09-06 15:59:27 +000012040 << (const NamedDecl *)M->first << Record;
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012041 Diag(M->first->getLocation(),
12042 diag::note_overridden_virtual_function);
12043 for (OverridingMethods::overriding_iterator
12044 OM = SO->second.begin(),
12045 OMEnd = SO->second.end();
12046 OM != OMEnd; ++OM)
12047 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divacky31ba6132012-09-06 15:59:27 +000012048 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor7a39dd02010-09-29 00:15:42 +000012049
12050 Record->setInvalidDecl();
12051 }
12052 }
12053 CXXRecord->completeDefinition(&FinalOverriders);
12054 Completed = true;
12055 }
12056 }
12057 }
12058 }
12059
12060 if (!Completed)
12061 Record->completeDefinition();
Sebastian Redl0ee33912011-05-19 05:13:44 +000012062
Richard Smithbe507b62013-02-01 08:12:08 +000012063 if (Record->hasAttrs())
12064 CheckAlignasUnderalignment(Record);
Serge Pavlov122e6012013-06-08 13:29:58 +000012065
12066 // Check if the structure/union declaration is a language extension.
12067 if (!getLangOpts().CPlusPlus) {
12068 bool ZeroSize = true;
Serge Pavlov0dcea352013-06-17 17:18:51 +000012069 bool IsEmpty = true;
12070 unsigned NonBitFields = 0;
Serge Pavlov122e6012013-06-08 13:29:58 +000012071 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlov0dcea352013-06-17 17:18:51 +000012072 E = Record->field_end();
12073 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12074 IsEmpty = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012075 if (I->isUnnamedBitfield()) {
Serge Pavlov122e6012013-06-08 13:29:58 +000012076 if (I->getBitWidthValue(Context) > 0)
12077 ZeroSize = false;
12078 } else {
Serge Pavlov0dcea352013-06-17 17:18:51 +000012079 ++NonBitFields;
12080 QualType FieldType = I->getType();
12081 if (FieldType->isIncompleteType() ||
12082 !Context.getTypeSizeInChars(FieldType).isZero())
12083 ZeroSize = false;
Serge Pavlov122e6012013-06-08 13:29:58 +000012084 }
12085 }
12086
12087 // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
12088 // C++.
Serge Pavlov0dcea352013-06-17 17:18:51 +000012089 if (ZeroSize)
12090 Diag(RecLoc, diag::warn_zero_size_struct_union_compat) << IsEmpty
12091 << Record->isUnion() << (NonBitFields > 1);
Serge Pavlov122e6012013-06-08 13:29:58 +000012092
12093 // Structs without named members are extension in C (C99 6.7.2.1p7), but
12094 // are accepted by GCC.
Serge Pavlov0dcea352013-06-17 17:18:51 +000012095 if (NonBitFields == 0) {
12096 if (IsEmpty)
Serge Pavlov122e6012013-06-08 13:29:58 +000012097 Diag(RecLoc, diag::ext_empty_struct_union) << Record->isUnion();
12098 else
12099 Diag(RecLoc, diag::ext_no_named_members_in_struct_union) << Record->isUnion();
12100 }
12101 }
Chris Lattnere1e79852008-02-06 00:51:33 +000012102 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +000012103 ObjCIvarDecl **ClsFields =
12104 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +000012105 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor05c272f2011-12-15 22:34:59 +000012106 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012107 // Add ivar's to class's DeclContext.
12108 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12109 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012110 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012111 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +000012112 // Must enforce the rule that ivars in the base classes may not be
12113 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +000012114 if (ID->getSuperClass())
12115 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +000012116 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +000012117 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +000012118 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +000012119 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12120 // Ivar declared in @implementation never belongs to the implementation.
12121 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +000012122 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +000012123 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012124 IMPDecl->setIvarLBraceLoc(LBrac);
12125 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012126 } else if (ObjCCategoryDecl *CDecl =
12127 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012128 // case of ivars in class extension; all other cases have been
12129 // reported as errors elsewhere.
12130 // FIXME. Class extension does not have a LocEnd field.
12131 // CDecl->setLocEnd(RBrac);
12132 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012133 // Diagnose redeclaration of private ivars.
12134 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012135 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012136 if (IDecl) {
12137 if (const ObjCIvarDecl *ClsIvar =
12138 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12139 Diag(ClsFields[i]->getLocation(),
12140 diag::err_duplicate_ivar_declaration);
12141 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12142 continue;
12143 }
Douglas Gregord3297242013-01-16 23:00:23 +000012144 for (ObjCInterfaceDecl::known_extensions_iterator
12145 Ext = IDecl->known_extensions_begin(),
12146 ExtEnd = IDecl->known_extensions_end();
12147 Ext != ExtEnd; ++Ext) {
12148 if (const ObjCIvarDecl *ClsExtIvar
12149 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian3ff86f72011-10-21 18:03:52 +000012150 Diag(ClsFields[i]->getLocation(),
12151 diag::err_duplicate_ivar_declaration);
12152 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12153 continue;
12154 }
12155 }
12156 }
Fariborz Jahanian0bd04592010-04-06 22:43:48 +000012157 ClsFields[i]->setLexicalDeclContext(CDecl);
12158 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +000012159 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +000012160 CDecl->setIvarLBraceLoc(LBrac);
12161 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +000012162 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +000012163 }
Daniel Dunbar7d076642008-10-03 17:33:35 +000012164
12165 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000012166 ProcessDeclAttributeList(S, Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +000012167}
12168
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012169/// \brief Determine whether the given integral value is representable within
12170/// the given type T.
12171static bool isRepresentableIntegerValue(ASTContext &Context,
12172 llvm::APSInt &Value,
12173 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012174 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +000012175 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012176
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012177 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor575a1c92011-05-20 16:38:50 +000012178 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012179 --BitWidth;
12180 return Value.getActiveBits() <= BitWidth;
12181 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012182 return Value.getMinSignedBits() <= BitWidth;
12183}
12184
12185// \brief Given an integral type, return the next larger integral type
12186// (or a NULL type of no such type exists).
12187static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12188 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12189 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +000012190 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012191 const unsigned NumTypes = 4;
12192 QualType SignedIntegralTypes[NumTypes] = {
12193 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12194 };
12195 QualType UnsignedIntegralTypes[NumTypes] = {
12196 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12197 Context.UnsignedLongLongTy
12198 };
12199
12200 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor575a1c92011-05-20 16:38:50 +000012201 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12202 : UnsignedIntegralTypes;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012203 for (unsigned I = 0; I != NumTypes; ++I)
12204 if (Context.getTypeSize(Types[I]) > BitWidth)
12205 return Types[I];
12206
12207 return QualType();
12208}
12209
Douglas Gregor879fd492009-03-17 19:05:46 +000012210EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12211 EnumConstantDecl *LastEnumConst,
12212 SourceLocation IdLoc,
12213 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +000012214 Expr *Val) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012215 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012216 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +000012217 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +000012218
12219 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12220 Val = 0;
12221
Eli Friedman19efa3e2011-12-06 00:10:34 +000012222 if (Val)
12223 Val = DefaultLvalueConversion(Val).take();
12224
Douglas Gregor4912c342009-11-06 00:03:12 +000012225 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012226 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +000012227 EltTy = Context.DependentTy;
12228 else {
Douglas Gregor4912c342009-11-06 00:03:12 +000012229 SourceLocation ExpLoc;
Richard Smith80ad52f2013-01-02 11:42:31 +000012230 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000012231 !getLangOpts().MicrosoftMode) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012232 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12233 // constant-expression in the enumerator-definition shall be a converted
12234 // constant expression of the underlying type.
12235 EltTy = Enum->getIntegerType();
12236 ExprResult Converted =
12237 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12238 CCEK_Enumerator);
12239 if (Converted.isInvalid())
12240 Val = 0;
12241 else
12242 Val = Converted.take();
12243 } else if (!Val->isValueDependent() &&
Richard Smith282e7e62012-02-04 09:53:13 +000012244 !(Val = VerifyIntegerConstantExpression(Val,
12245 &EnumVal).take())) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012246 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smith8ef7b202012-01-18 23:55:52 +000012247 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012248 if (Enum->isFixed()) {
12249 EltTy = Enum->getIntegerType();
12250
Richard Smith8ef7b202012-01-18 23:55:52 +000012251 // In Obj-C and Microsoft mode, require the enumeration value to be
12252 // representable in the underlying type of the enumeration. In C++11,
12253 // we perform a non-narrowing conversion as part of converted constant
12254 // expression checking.
Francois Pichet842e7a22010-10-18 15:01:13 +000012255 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012256 if (getLangOpts().MicrosoftMode) {
Francois Pichet842e7a22010-10-18 15:01:13 +000012257 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley429bb272011-04-08 18:41:53 +000012258 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smith8ef7b202012-01-18 23:55:52 +000012259 } else
12260 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Pichet842e7a22010-10-18 15:01:13 +000012261 } else
John Wiegley429bb272011-04-08 18:41:53 +000012262 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +000012263 } else if (getLangOpts().CPlusPlus) {
Richard Smith8ef7b202012-01-18 23:55:52 +000012264 // C++11 [dcl.enum]p5:
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012265 // If the underlying type is not fixed, the type of each enumerator
12266 // is the type of its initializing value:
12267 // - If an initializer is specified for an enumerator, the
12268 // initializing value has the same type as the expression.
12269 EltTy = Val->getType();
Eli Friedman04ca2522012-02-07 04:34:38 +000012270 } else {
12271 // C99 6.7.2.2p2:
12272 // The expression that defines the value of an enumeration constant
12273 // shall be an integer constant expression that has a value
12274 // representable as an int.
12275
12276 // Complain if the value is not representable in an int.
12277 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12278 Diag(IdLoc, diag::ext_enum_value_not_int)
12279 << EnumVal.toString(10) << Val->getSourceRange()
12280 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12281 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12282 // Force the type of the expression to 'int'.
12283 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12284 }
12285 EltTy = Val->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012286 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012287 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012288 }
12289 }
Mike Stump1eb44332009-09-09 15:08:12 +000012290
Douglas Gregor879fd492009-03-17 19:05:46 +000012291 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012292 if (Enum->isDependentType())
12293 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012294 else if (!LastEnumConst) {
12295 // C++0x [dcl.enum]p5:
12296 // If the underlying type is not fixed, the type of each enumerator
12297 // is the type of its initializing value:
12298 // - If no initializer is specified for the first enumerator, the
12299 // initializing value has an unspecified integral type.
12300 //
12301 // GCC uses 'int' for its unspecified integral type, as does
12302 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012303 if (Enum->isFixed()) {
12304 EltTy = Enum->getIntegerType();
12305 }
12306 else {
12307 EltTy = Context.IntTy;
12308 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012309 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +000012310 // Assign the last value + 1.
12311 EnumVal = LastEnumConst->getInitVal();
12312 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012313 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +000012314
12315 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012316 if (EnumVal < LastEnumConst->getInitVal()) {
12317 // C++0x [dcl.enum]p5:
12318 // If the underlying type is not fixed, the type of each enumerator
12319 // is the type of its initializing value:
12320 //
12321 // - Otherwise the type of the initializing value is the same as
12322 // the type of the initializing value of the preceding enumerator
12323 // unless the incremented value is not representable in that type,
12324 // in which case the type is an unspecified integral type
12325 // sufficient to contain the incremented value. If no such type
12326 // exists, the program is ill-formed.
12327 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012328 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012329 // There is no integral type larger enough to represent this
12330 // value. Complain, then allow the value to wrap around.
12331 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +000012332 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012333 ++EnumVal;
12334 if (Enum->isFixed())
12335 // When the underlying type is fixed, this is ill-formed.
12336 Diag(IdLoc, diag::err_enumerator_wrapped)
12337 << EnumVal.toString(10)
12338 << EltTy;
12339 else
12340 Diag(IdLoc, diag::warn_enumerator_too_large)
12341 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012342 } else {
12343 EltTy = T;
12344 }
12345
12346 // Retrieve the last enumerator's value, extent that type to the
12347 // type that is supposed to be large enough to represent the incremented
12348 // value, then increment.
12349 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor575a1c92011-05-20 16:38:50 +000012350 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad9f71a8f2010-12-07 08:25:34 +000012351 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012352 ++EnumVal;
12353
12354 // If we're not in C++, diagnose the overflow of enumerator values,
12355 // which in C99 means that the enumerator value is not representable in
12356 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12357 // permits enumerator values that are representable in some larger
12358 // integral type.
David Blaikie4e4d0842012-03-11 07:00:24 +000012359 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012360 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikie4e4d0842012-03-11 07:00:24 +000012361 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012362 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12363 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12364 Diag(IdLoc, diag::ext_enum_value_not_int)
12365 << EnumVal.toString(10) << 1;
12366 }
Douglas Gregor879fd492009-03-17 19:05:46 +000012367 }
12368 }
Mike Stump1eb44332009-09-09 15:08:12 +000012369
Douglas Gregor9b9edd62010-03-02 17:53:14 +000012370 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012371 // Make the enumerator value match the signedness and size of the
12372 // enumerator's type.
Eli Friedman04ca2522012-02-07 04:34:38 +000012373 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor575a1c92011-05-20 16:38:50 +000012374 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012375 }
Douglas Gregor4912c342009-11-06 00:03:12 +000012376
Douglas Gregor879fd492009-03-17 19:05:46 +000012377 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +000012378 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +000012379}
12380
12381
John McCall5b629aa2010-10-22 23:36:17 +000012382Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12383 SourceLocation IdLoc, IdentifierInfo *Id,
12384 AttributeList *Attr,
Richard Smith8ef7b202012-01-18 23:55:52 +000012385 SourceLocation EqualLoc, Expr *Val) {
John McCalld226f652010-08-21 09:40:31 +000012386 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +000012387 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +000012388 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +000012389
Chris Lattner31e05722007-08-26 06:24:45 +000012390 // The scope passed in may not be a decl scope. Zip up the scope tree until
12391 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +000012392 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +000012393
Reid Spencer5f016e22007-07-11 17:01:13 +000012394 // Verify that there isn't already something declared with this name in this
12395 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +000012396 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +000012397 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +000012398 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +000012399 // Maybe we will complain about the shadowed template parameter.
12400 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12401 // Just pretend that we didn't see the previous declaration.
12402 PrevDecl = 0;
12403 }
12404
12405 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012406 // When in C++, we may get a TagDecl with the same name; in this case the
12407 // enum constant will 'hide' the tag.
David Blaikie4e4d0842012-03-11 07:00:24 +000012408 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +000012409 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000012410 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012411 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +000012412 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +000012413 else
Chris Lattner3c73c412008-11-19 08:23:25 +000012414 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +000012415 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +000012416 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000012417 }
12418 }
12419
Aaron Ballmanf8167872012-07-19 03:12:23 +000012420 // C++ [class.mem]p15:
12421 // If T is the name of a class, then each of the following shall have a name
12422 // different from T:
12423 // - every enumerator of every member of class T that is an unscoped
12424 // enumerated type
Douglas Gregora6e937c2010-10-15 13:21:21 +000012425 if (CXXRecordDecl *Record
12426 = dyn_cast<CXXRecordDecl>(
12427 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballmanf8167872012-07-19 03:12:23 +000012428 if (!TheEnumDecl->isScoped() &&
12429 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregora6e937c2010-10-15 13:21:21 +000012430 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12431
John McCall5b629aa2010-10-22 23:36:17 +000012432 EnumConstantDecl *New =
12433 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +000012434
John McCall92f88312010-01-23 00:46:32 +000012435 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +000012436 // Process attributes.
12437 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12438
12439 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +000012440 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +000012441 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +000012442 }
Douglas Gregor45579f52008-12-17 02:04:30 +000012443
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000012444 ActOnDocumentableDecl(New);
12445
John McCalld226f652010-08-21 09:40:31 +000012446 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +000012447}
12448
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012449// Returns true when the enum initial expression does not trigger the
12450// duplicate enum warning. A few common cases are exempted as follows:
12451// Element2 = Element1
12452// Element2 = Element1 + 1
12453// Element2 = Element1 - 1
12454// Where Element2 and Element1 are from the same enum.
12455static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12456 Expr *InitExpr = ECD->getInitExpr();
12457 if (!InitExpr)
12458 return true;
12459 InitExpr = InitExpr->IgnoreImpCasts();
12460
12461 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12462 if (!BO->isAdditiveOp())
12463 return true;
12464 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12465 if (!IL)
12466 return true;
12467 if (IL->getValue() != 1)
12468 return true;
12469
12470 InitExpr = BO->getLHS();
12471 }
12472
12473 // This checks if the elements are from the same enum.
12474 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12475 if (!DRE)
12476 return true;
12477
12478 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12479 if (!EnumConstant)
12480 return true;
12481
12482 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12483 Enum)
12484 return true;
12485
12486 return false;
12487}
12488
12489struct DupKey {
12490 int64_t val;
12491 bool isTombstoneOrEmptyKey;
12492 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12493 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12494};
12495
12496static DupKey GetDupKey(const llvm::APSInt& Val) {
12497 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12498 false);
12499}
12500
12501struct DenseMapInfoDupKey {
12502 static DupKey getEmptyKey() { return DupKey(0, true); }
12503 static DupKey getTombstoneKey() { return DupKey(1, true); }
12504 static unsigned getHashValue(const DupKey Key) {
12505 return (unsigned)(Key.val * 37);
12506 }
12507 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12508 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12509 LHS.val == RHS.val;
12510 }
12511};
12512
12513// Emits a warning when an element is implicitly set a value that
12514// a previous element has already been set to.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012515static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12516 EnumDecl *Enum,
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012517 QualType EnumType) {
12518 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12519 Enum->getLocation()) ==
12520 DiagnosticsEngine::Ignored)
12521 return;
12522 // Avoid anonymous enums
12523 if (!Enum->getIdentifier())
12524 return;
12525
12526 // Only check for small enums.
12527 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12528 return;
12529
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012530 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12531 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012532
12533 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12534 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12535 ValueToVectorMap;
12536
12537 DuplicatesVector DupVector;
12538 ValueToVectorMap EnumMap;
12539
12540 // Populate the EnumMap with all values represented by enum constants without
12541 // an initialier.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012542 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramerefac8da2013-04-07 14:10:40 +000012543 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012544
12545 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12546 // this constant. Skip this enum since it may be ill-formed.
12547 if (!ECD) {
12548 return;
12549 }
12550
12551 if (ECD->getInitExpr())
12552 continue;
12553
12554 DupKey Key = GetDupKey(ECD->getInitVal());
12555 DeclOrVector &Entry = EnumMap[Key];
12556
12557 // First time encountering this value.
12558 if (Entry.isNull())
12559 Entry = ECD;
12560 }
12561
12562 // Create vectors for any values that has duplicates.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012563 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012564 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12565 if (!ValidDuplicateEnum(ECD, Enum))
12566 continue;
12567
12568 DupKey Key = GetDupKey(ECD->getInitVal());
12569
12570 DeclOrVector& Entry = EnumMap[Key];
12571 if (Entry.isNull())
12572 continue;
12573
12574 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12575 // Ensure constants are different.
12576 if (D == ECD)
12577 continue;
12578
12579 // Create new vector and push values onto it.
12580 ECDVector *Vec = new ECDVector();
12581 Vec->push_back(D);
12582 Vec->push_back(ECD);
12583
12584 // Update entry to point to the duplicates vector.
12585 Entry = Vec;
12586
12587 // Store the vector somewhere we can consult later for quick emission of
12588 // diagnostics.
12589 DupVector.push_back(Vec);
12590 continue;
12591 }
12592
12593 ECDVector *Vec = Entry.get<ECDVector*>();
12594 // Make sure constants are not added more than once.
12595 if (*Vec->begin() == ECD)
12596 continue;
12597
12598 Vec->push_back(ECD);
12599 }
12600
12601 // Emit diagnostics.
12602 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12603 DupVectorEnd = DupVector.end();
12604 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12605 ECDVector *Vec = *DupVectorIter;
12606 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12607
12608 // Emit warning for one enum constant.
12609 ECDVector::iterator I = Vec->begin();
12610 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12611 << (*I)->getName() << (*I)->getInitVal().toString(10)
12612 << (*I)->getSourceRange();
12613 ++I;
12614
12615 // Emit one note for each of the remaining enum constants with
12616 // the same value.
12617 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12618 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12619 << (*I)->getName() << (*I)->getInitVal().toString(10)
12620 << (*I)->getSourceRange();
12621 delete Vec;
12622 }
12623}
12624
Mike Stumpc6e35aa2009-05-16 07:06:02 +000012625void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +000012626 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012627 ArrayRef<Decl *> Elements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012628 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +000012629 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +000012630 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012631
12632 if (Attr)
12633 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +000012634
Eli Friedmaned0716b2009-12-11 01:34:50 +000012635 if (Enum->isDependentType()) {
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012636 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmaned0716b2009-12-11 01:34:50 +000012637 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012638 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012639 if (!ECD) continue;
12640
12641 ECD->setType(EnumType);
12642 }
12643
John McCall1b5a6182010-05-06 08:49:23 +000012644 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +000012645 return;
12646 }
12647
Chris Lattnere37f0be2007-08-28 05:10:31 +000012648 // TODO: If the result value doesn't fit in an int, it must be a long or long
12649 // long value. ISO C does not support this, but GCC does as an extension,
12650 // emit a warning.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012651 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12652 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12653 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012654
Chris Lattnerac609682007-08-28 06:15:15 +000012655 // Verify that all the values are okay, compute the size of the values, and
12656 // reverse the list.
12657 unsigned NumNegativeBits = 0;
12658 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000012659
Chris Lattnerac609682007-08-28 06:15:15 +000012660 // Keep track of whether all elements have type int.
12661 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +000012662
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012663 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Reid Spencer5f016e22007-07-11 17:01:13 +000012664 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +000012665 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +000012666 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +000012667
Chris Lattner211a30e2007-08-28 05:27:00 +000012668 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +000012669
Chris Lattnerac609682007-08-28 06:15:15 +000012670 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +000012671 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +000012672 NumPositiveBits = std::max(NumPositiveBits,
12673 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +000012674 else
Chris Lattner21dd8212008-01-14 21:47:29 +000012675 NumNegativeBits = std::max(NumNegativeBits,
12676 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +000012677
Chris Lattnerac609682007-08-28 06:15:15 +000012678 // Keep track of whether every enum element has type int (very commmon).
12679 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +000012680 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +000012681 }
Mike Stump1eb44332009-09-09 15:08:12 +000012682
Chris Lattnerac609682007-08-28 06:15:15 +000012683 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +000012684 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012685 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012686
John McCall842aef82009-12-09 09:09:27 +000012687 // C++0x N3000 [conv.prom]p3:
12688 // An rvalue of an unscoped enumeration type whose underlying
12689 // type is not fixed can be converted to an rvalue of the first
12690 // of the following types that can represent all the values of
12691 // the enumeration: int, unsigned int, long int, unsigned long
12692 // int, long long int, or unsigned long long int.
12693 // C99 6.4.4.3p2:
12694 // An identifier declared as an enumeration constant has type int.
12695 // The C99 rule is modified by a gcc extension
12696 QualType BestPromotionType;
12697
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012698 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +000012699 // -fshort-enums is the equivalent to specifying the packed attribute on all
12700 // enum definitions.
12701 if (LangOpts.ShortEnums)
12702 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012703
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012704 if (Enum->isFixed()) {
Eli Friedman3bfb5712011-10-26 07:38:19 +000012705 BestType = Enum->getIntegerType();
12706 if (BestType->isPromotableIntegerType())
12707 BestPromotionType = Context.getPromotedIntegerType(BestType);
12708 else
12709 BestPromotionType = BestType;
Duncan Sands240a0202010-10-12 14:07:59 +000012710 // We don't need to set BestWidth, because BestType is going to be the type
12711 // of the enumerators, but we do anyway because otherwise some compilers
12712 // warn that it might be used uninitialized.
12713 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +000012714 }
12715 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +000012716 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +000012717 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012718 // If it's packed, check also if it fits a char or a short.
12719 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012720 BestType = Context.SignedCharTy;
12721 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +000012722 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012723 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012724 BestType = Context.ShortTy;
12725 BestWidth = ShortWidth;
12726 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012727 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012728 BestWidth = IntWidth;
12729 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012730 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012731
John McCall842aef82009-12-09 09:09:27 +000012732 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012733 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +000012734 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012735 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +000012736
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012737 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +000012738 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12739 BestType = Context.LongLongTy;
12740 }
12741 }
John McCall842aef82009-12-09 09:09:27 +000012742 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +000012743 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012744 // If there is no negative value, figure out the smallest type that fits
12745 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012746 // If it's packed, check also if it fits a char or a short.
12747 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +000012748 BestType = Context.UnsignedCharTy;
12749 BestPromotionType = Context.IntTy;
12750 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +000012751 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +000012752 BestType = Context.UnsignedShortTy;
12753 BestPromotionType = Context.IntTy;
12754 BestWidth = ShortWidth;
12755 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +000012756 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012757 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012758 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012759 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012760 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012761 } else if (NumPositiveBits <=
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012762 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +000012763 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012764 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012765 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012766 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +000012767 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000012768 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012769 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +000012770 "How could an initializer get larger than ULL?");
12771 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012772 BestPromotionType
David Blaikie4e4d0842012-03-11 07:00:24 +000012773 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +000012774 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +000012775 }
12776 }
Mike Stump1eb44332009-09-09 15:08:12 +000012777
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012778 // Loop over all of the enumerator constants, changing their types to match
12779 // the type of the enum if needed.
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012780 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +000012781 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012782 if (!ECD) continue; // Already issued a diagnostic.
12783
12784 // Standard C says the enumerators have int type, but we allow, as an
12785 // extension, the enumerators to be larger than int size. If each
12786 // enumerator value fits in an int, type it as an int, otherwise type it the
12787 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12788 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012789
12790 // Determine whether the value fits into an int.
12791 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012792
12793 // If it fits into an integer type, force it. Otherwise force it to match
12794 // the enum decl type.
12795 QualType NewTy;
12796 unsigned NewWidth;
12797 bool NewSign;
David Blaikie4e4d0842012-03-11 07:00:24 +000012798 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3b252162011-11-04 18:51:24 +000012799 !Enum->isFixed() &&
Douglas Gregor677e4fe2010-02-01 23:36:03 +000012800 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012801 NewTy = Context.IntTy;
12802 NewWidth = IntWidth;
12803 NewSign = true;
12804 } else if (ECD->getType() == BestType) {
12805 // Already the right type!
David Blaikie4e4d0842012-03-11 07:00:24 +000012806 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012807 // C++ [dcl.enum]p4: Following the closing brace of an
12808 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012809 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012810 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012811 continue;
12812 } else {
12813 NewTy = BestType;
12814 NewWidth = BestWidth;
Douglas Gregor575a1c92011-05-20 16:38:50 +000012815 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012816 }
12817
12818 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +000012819 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012820 InitVal.setIsSigned(NewSign);
12821 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +000012822
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012823 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +000012824 if (ECD->getInitExpr() &&
Nick Lewycky25af0912011-07-02 02:05:12 +000012825 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +000012826 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +000012827 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +000012828 ECD->getInitExpr(),
12829 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +000012830 VK_RValue));
David Blaikie4e4d0842012-03-11 07:00:24 +000012831 if (getLangOpts().CPlusPlus)
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012832 // C++ [dcl.enum]p4: Following the closing brace of an
12833 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +000012834 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +000012835 ECD->setType(EnumType);
12836 else
12837 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +000012838 }
Mike Stump1eb44332009-09-09 15:08:12 +000012839
John McCall1b5a6182010-05-06 08:49:23 +000012840 Enum->completeDefinition(BestType, BestPromotionType,
12841 NumPositiveBits, NumNegativeBits);
James Molloy16f1f712012-02-29 10:24:19 +000012842
12843 // If we're declaring a function, ensure this decl isn't forgotten about -
12844 // it needs to go into the function scope.
12845 if (InFunctionDeclarator)
12846 DeclsInPrototypeScope.push_back(Enum);
Ted Kremeneka734a0e2012-12-22 01:34:09 +000012847
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +000012848 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smithbe507b62013-02-01 08:12:08 +000012849
12850 // Now that the enum type is defined, ensure it's not been underaligned.
12851 if (Enum->hasAttrs())
12852 CheckAlignasUnderalignment(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +000012853}
12854
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012855Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12856 SourceLocation StartLoc,
12857 SourceLocation EndLoc) {
John McCall9ae2f072010-08-23 23:25:46 +000012858 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +000012859
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +000012860 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara21e006e2011-03-03 14:20:18 +000012861 AsmString, StartLoc,
12862 EndLoc);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012863 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +000012864 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +000012865}
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012866
Douglas Gregor5948ae12012-01-03 18:04:46 +000012867DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12868 SourceLocation ImportLoc,
12869 ModuleIdPath Path) {
Douglas Gregor5e356932011-12-01 17:11:21 +000012870 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +000012871 Module::AllVisible,
12872 /*IsIncludeDirective=*/false);
Douglas Gregor1a4761e2011-11-30 23:21:26 +000012873 if (!Mod)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012874 return true;
12875
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012876 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregor15de72c2011-12-02 23:23:56 +000012877 Module *ModCheck = Mod;
12878 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12879 // If we've run out of module parents, just drop the remaining identifiers.
12880 // We need the length to be consistent.
12881 if (!ModCheck)
12882 break;
12883 ModCheck = ModCheck->Parent;
12884
12885 IdentifierLocs.push_back(Path[I].second);
12886 }
12887
12888 ImportDecl *Import = ImportDecl::Create(Context,
12889 Context.getTranslationUnitDecl(),
Douglas Gregor5948ae12012-01-03 18:04:46 +000012890 AtLoc.isValid()? AtLoc : ImportLoc,
12891 Mod, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +000012892 Context.getTranslationUnitDecl()->addDecl(Import);
12893 return Import;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000012894}
12895
Douglas Gregorca2ab452013-01-12 01:29:50 +000012896void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12897 // Create the implicit import declaration.
12898 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12899 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12900 Loc, Mod, Loc);
12901 TU->addDecl(ImportD);
12902 Consumer.HandleImplicitImportDecl(ImportD);
12903
12904 // Make the module visible.
Douglas Gregor906d66a2013-03-20 21:10:35 +000012905 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12906 /*Complain=*/false);
Douglas Gregorca2ab452013-01-12 01:29:50 +000012907}
12908
David Chisnall5f3c1632012-02-18 16:12:34 +000012909void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12910 IdentifierInfo* AliasName,
12911 SourceLocation PragmaLoc,
12912 SourceLocation NameLoc,
12913 SourceLocation AliasNameLoc) {
12914 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12915 LookupOrdinaryName);
12916 AsmLabelAttr *Attr =
12917 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall5f3c1632012-02-18 16:12:34 +000012918
12919 if (PrevDecl)
12920 PrevDecl->addAttr(Attr);
12921 else
12922 (void)ExtnameUndeclaredIdentifiers.insert(
12923 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12924}
12925
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012926void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12927 SourceLocation PragmaLoc,
12928 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012929 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012930
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012931 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +000012932 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +000012933 } else {
12934 (void)WeakUndeclaredIdentifiers.insert(
12935 std::pair<IdentifierInfo*,WeakInfo>
12936 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012937 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012938}
12939
12940void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12941 IdentifierInfo* AliasName,
12942 SourceLocation PragmaLoc,
12943 SourceLocation NameLoc,
12944 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +000012945 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12946 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +000012947 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012948
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012949 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +000012950 if (!PrevDecl->hasAttr<AliasAttr>())
12951 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +000012952 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +000012953 } else {
12954 (void)WeakUndeclaredIdentifiers.insert(
12955 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012956 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +000012957}
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000012958
12959Decl *Sema::getObjCDeclContext() const {
12960 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12961}
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012962
12963AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian3359fa32012-09-06 18:38:58 +000012964 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +000012965 return D->getAvailability();
12966}