blob: c17510ae8a78eb64d59f3bbbf91c97f20d7f5958 [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregor844cb502011-03-01 18:12:44 +000015#include "TypeLocBuilder.h"
Chris Lattner622c1932008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000017#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000018#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000021#include "clang/AST/CommentDiagnostic.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Chandler Carruth33bf3e72011-03-27 09:46:56 +000025#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000026#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000027#include "clang/AST/StmtCXX.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000029#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-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 Valia17d19f2013-11-07 05:17:06 +000043#include "clang/Sema/Template.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000044#include "llvm/ADT/SmallString.h"
John McCall0e21fcc2009-12-24 09:58:38 +000045#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000046#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000047#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000048#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000049using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000050using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000051
Richard Smithcd1c0552011-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 McCall48871652010-08-21 09:40:31 +000058 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000059}
60
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000061namespace {
62
63class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64 public:
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000065 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
66 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
Kaelyn Uhrainb1378402012-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 Uhrain9cb8e9f2012-06-22 23:37:05 +000077 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000078 }
79
80 private:
81 bool AllowInvalidDecl;
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000082 bool WantClassName;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000083};
84
85}
86
Kaelyn Uhrain237c7d32012-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 Majnemera5e92552013-09-22 01:24:26 +0000113 case tok::annot_decltype:
Kaelyn Uhrain237c7d32012-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 Gregorec6e1892009-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 Gregor9817f4a2009-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 Gribenko5267fdf2013-05-03 13:12:11 +0000132ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallba7bf592010-08-24 05:47:05 +0000133 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +0000134 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +0000135 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000136 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000137 bool WantNontrivialTypeSourceInfo,
138 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000139 // Determine where we will perform name lookup.
140 DeclContext *LookupCtx = 0;
141 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000142 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000143 if (ObjectType->isRecordType())
144 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000145 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-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 Smith23d55872012-04-02 01:30:27 +0000159 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000160 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000161
John McCallc392f372010-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 Gregor844cb502011-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 McCallba7bf592010-08-24 05:47:05 +0000168 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000169 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000170 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000171
172 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000173 }
174
John McCallba7bf592010-08-24 05:47:05 +0000175 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000176 }
177
John McCall0b66eb32010-05-01 00:40:08 +0000178 if (!LookupCtx->isDependentContext() &&
179 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000180 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000181 }
Eli Friedman9025ec22009-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 Gregora25d65d2009-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 Gregorc9f9b862009-05-11 19:58:34 +0000194
Douglas Gregora25d65d2009-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 Lattnera3778332009-02-16 22:07:16 +0000209 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000210 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000211 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000212 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000213 if (CorrectedII) {
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +0000214 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000215 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000216 Kind, S, SS, Validator);
Kaelyn Uhrain85308c62011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000232 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-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 Bagnara4244b432012-01-27 08:46:19 +0000237 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000238 WantNontrivialTypeSourceInfo);
239 if (Ty) {
Richard Smithf9b15102013-08-17 00:46:16 +0000240 diagnoseTypo(Correction,
241 PDiag(diag::err_unknown_type_or_class_name_suggest)
242 << Result.getLookupName() << isClassName);
Kaelyn Uhrain85308c62011-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 Lattnera3778332009-02-16 22:07:16 +0000251 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000252 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000253 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000254 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000255
Chris Lattnere40853a2009-10-25 22:09:09 +0000256 case LookupResult::Ambiguous:
John McCall6538c932009-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 McCall27b18f82009-11-17 02:14:36 +0000262 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
263 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000264 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000265 }
John McCall6538c932009-10-10 05:48:19 +0000266
Douglas Gregorfe3d7d02009-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 Stump11289f42009-09-09 15:08:12 +0000271 if (!IIDecl ||
272 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000273 IIDecl->getLocation().getRawEncoding())
274 IIDecl = *Res;
Douglas Gregorfe3d7d02009-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 McCall27b18f82009-11-17 02:14:36 +0000285 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000286 return ParsedType();
Douglas Gregorfe3d7d02009-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 Gregorfe3d7d02009-04-01 21:51:26 +0000293 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000294
Chris Lattnera3778332009-02-16 22:07:16 +0000295 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000296 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000297 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000298 }
299
Chris Lattner17e15f12009-10-25 17:16:46 +0000300 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000301
Chris Lattner17e15f12009-10-25 17:16:46 +0000302 QualType T;
303 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000304 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000305
Chris Lattner17e15f12009-10-25 17:16:46 +0000306 if (T.isNull())
307 T = Context.getTypeDeclType(TD);
Abramo Bagnara4244b432012-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 Gregor844cb502011-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 Bagnara9033e2b2012-02-06 19:09:27 +0000320 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor844cb502011-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 Lattner17e15f12009-10-25 17:16:46 +0000327 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000328 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000329 if (!HasTrailingDot)
330 T = Context.getObjCInterfaceType(IDecl);
331 }
332
333 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000334 // If it's not plausibly a type, suppress diagnostics.
335 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000336 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000337 }
John McCallba7bf592010-08-24 05:47:05 +0000338 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000339}
340
Chris Lattnerffaa0e62009-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 Matosdc86f942012-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 Lattnerffaa0e62009-04-12 21:49:30 +0000346DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
347 // Do a tag name lookup in this scope.
John McCall27b18f82009-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 McCall67c00872009-12-02 08:25:40 +0000352 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000353 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000354 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matosdc86f942012-08-31 18:45:21 +0000355 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara6150c882010-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 Lattnerffaa0e62009-04-12 21:49:30 +0000359 }
360 }
Mike Stump11289f42009-09-09 15:08:12 +0000361
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000362 return DeclSpec::TST_unspecified;
363}
364
Francois Pichet48c946e2011-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 Pichet9a57fb52011-10-11 01:50:09 +0000379bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000380 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000381 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-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 Pichet9a57fb52011-10-11 01:50:09 +0000388 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000389 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000390 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000391}
392
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000393bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000394 SourceLocation IILoc,
395 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000396 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000397 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000398 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000399 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000400
Douglas Gregor2d435302009-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 Uhrainb1378402012-01-18 21:41:41 +0000403 TypeNameValidatorCCC Validator(false);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000404 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000405 LookupOrdinaryName, S, SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000406 Validator)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000407 if (Corrected.isKeyword()) {
408 // We corrected to a keyword.
Richard Smithf9b15102013-08-17 00:46:16 +0000409 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
410 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000411 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000412 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000413 if (!SS || !SS->isSet()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000414 diagnoseTypo(Corrected,
415 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000416 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000417 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
418 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000419 II->getName().equals(CorrectedStr);
Richard Smithf9b15102013-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 Uhrainb1378402012-01-18 21:41:41 +0000424 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000425 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000426
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000427 CXXScopeSpec tmpSS;
428 if (Corrected.getCorrectionSpecifier())
429 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
430 SourceRange(IILoc));
Richard Smithf9b15102013-08-17 00:46:16 +0000431 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000432 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
433 false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000434 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000435 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000436 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000437 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000438 }
439
David Blaikiebbafb8a2012-03-11 07:00:24 +0000440 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-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 Uhrainb5b17fe2012-06-15 23:45:58 +0000443 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000444 CXXScopeSpec EmptySS;
445 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000446 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000447 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000448 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000449 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +0000450 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskin54eba422010-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 Gregor15e56022009-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 Gregor2d435302009-12-30 17:04:44 +0000463 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000464 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000465 else if (DeclContext *DC = computeDeclContext(*SS, false))
466 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000467 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000468 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000469 unsigned DiagID = diag::err_typename_missing;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000471 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000472
473 Diag(SS->getRange().getBegin(), DiagID)
Aaron Ballman691e2272014-01-03 14:48:20 +0000474 << SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000475 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000476 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000477 SuggestedType = ActOnTypenameType(S, SourceLocation(),
478 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-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 Lattnerffaa0e62009-04-12 21:49:30 +0000486
Douglas Gregor0e7dde52011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000490 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-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 Uhrain71792052012-05-02 00:11:40 +0000504static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
505 Scope *S, CXXScopeSpec &SS,
506 IdentifierInfo *&Name,
507 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-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 Uhrain71792052012-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 Matosdc86f942012-08-31 18:45:21 +0000529 case TTK_Interface:
530 TagName = "__interface";
531 FixItTagName = "__interface ";
532 break;
533
Kaelyn Uhrain71792052012-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 Smithaa31b4b2012-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 Uhrain71792052012-05-02 00:11:40 +0000552 return true;
553 }
554
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000555 return false;
556}
557
Richard Smith4f605af2012-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 Gregor0e7dde52011-04-24 05:37:28 +0000573Sema::NameClassification Sema::ClassifyName(Scope *S,
574 CXXScopeSpec &SS,
575 IdentifierInfo *&Name,
576 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000577 const Token &NextToken,
578 bool IsAddressOfOperand,
579 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-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 Gregorb90f5182011-04-25 15:05:41 +0000598 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000599 return E;
Douglas Gregor0e7dde52011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000613 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-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 Uhrain71792052012-05-02 00:11:40 +0000638 if (!getLangOpts().CPlusPlus && !SecondTry &&
639 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
640 break;
Douglas Gregor0e7dde52011-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 Smith4f605af2012-08-18 00:55:03 +0000645 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000646 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000647 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000648 Result.getLookupKind(), S,
Richard Smith4f605af2012-08-18 00:55:03 +0000649 &SS, *CCC)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000650 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
651 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000652
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000653 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000654 NamedDecl *UnderlyingFirstDecl
655 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000656 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000657 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000658 UnqualifiedDiag = diag::err_no_template_suggest;
659 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000660 } else if (UnderlyingFirstDecl &&
661 (isa<TypeDecl>(UnderlyingFirstDecl) ||
662 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
663 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000664 UnqualifiedDiag = diag::err_unknown_typename_suggest;
665 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
666 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000667
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000668 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000669 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000670 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000671 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
672 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000673 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000674 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
675 << Name << computeDeclContext(SS, false)
676 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000677 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000678
679 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000680 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000681
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000682 // Typo correction corrected to a keyword.
683 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000684 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000685
Douglas Gregorc2fa1692011-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 Smithf9b15102013-08-17 00:46:16 +0000690 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000691 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-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 Kramer62b95d82012-08-23 21:35:17 +0000700 return E;
Douglas Gregor0e7dde52011-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 Bagnara7945c982012-01-27 09:46:47 +0000711 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-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 Smith4f605af2012-08-18 00:55:03 +0000726 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
727 NameInfo, IsAddressOfOperand,
728 /*TemplateArgs=*/0);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000729 }
Douglas Gregor0e7dde52011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000737 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000738 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000761 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-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 Gregor8b02cd02011-04-27 04:48:22 +0000772 if (!Result.empty()) {
773 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000774 bool IsVarTemplate;
Douglas Gregor8b02cd02011-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 Voufo39a1e502013-08-06 01:03:05 +0000784 IsVarTemplate = isa<VarTemplateDecl>(TD);
785
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000786 if (SS.isSet() && !SS.isInvalid())
787 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000788 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000789 TD);
790 else
791 Template = TemplateName(TD);
792 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000793
Douglas Gregor8b02cd02011-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 Voufo39a1e502013-08-06 01:03:05 +0000802
803 return IsVarTemplate ? NameClassification::VarTemplate(Template)
804 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000805 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000806 }
Richard Smith4f605af2012-08-18 00:55:03 +0000807
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000808 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000809 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
810 DiagnoseUseOfDecl(Type, NameLoc);
811 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000812 if (SS.isNotEmpty())
813 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000814 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000815 }
Richard Smith4f605af2012-08-18 00:55:03 +0000816
Douglas Gregor0e7dde52011-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 Uhrain71792052012-05-02 00:11:40 +0000838
Richard Smith4f605af2012-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 Uhrain71792052012-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 Kyrtzidisc64c0292013-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 Uhrain71792052012-05-02 00:11:40 +0000856 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000857
Richard Smith4f605af2012-08-18 00:55:03 +0000858 if (FirstDecl->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000859 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000860
Douglas Gregor0e7dde52011-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 McCall5ed6e8f2009-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 Kyrtzidis16ac9be2008-11-08 17:17:31 +0000868DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000869
John McCall5ed6e8f2009-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.
Faisal Valibb9071e2013-12-04 22:43:08 +0000873 // A Lambda call operator whose parent is a class must not be treated
874 // as an inline member function. A Lambda can be used legally
875 // either as an in-class member initializer or a default argument. These
876 // are parsed once the class has been marked complete and so the containing
877 // context would be the nested class (when the lambda is defined in one);
878 // If the class is not complete, then the lambda is being used in an
879 // ill-formed fashion (such as to specify the width of a bit-field, or
880 // in an array-bound) - in which case we still want to return the
881 // lexically containing DC (which could be a nested class).
882 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +0000883 DC = DC->getLexicalParent();
884
885 // A function not defined within a class will always return to its
886 // lexical context.
887 if (!isa<CXXRecordDecl>(DC))
888 return DC;
889
890 // A C++ inline method/friend is parsed *after* the topmost class
891 // it was declared in is fully parsed ("complete"); the topmost
892 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000893 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000894 DC = RD;
895
896 // Return the declaration context of the topmost class the inline method is
897 // declared in.
898 return DC;
899 }
900
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000901 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000902}
903
Douglas Gregor91f84212008-12-11 16:49:14 +0000904void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000905 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000906 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000907 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000908 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000909}
910
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000911void Sema::PopDeclContext() {
912 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000913
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000914 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000915 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000916}
917
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000918/// EnterDeclaratorContext - Used when we must lookup names in the context
919/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000920///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000921void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000922 // C++0x [basic.lookup.unqual]p13:
923 // A name used in the definition of a static data member of class
924 // X (after the qualified-id of the static member) is looked up as
925 // if the name was used in a member function of X.
926 // C++0x [basic.lookup.unqual]p14:
927 // If a variable member of a namespace is defined outside of the
928 // scope of its namespace then any name used in the definition of
929 // the variable member (after the declarator-id) is looked up as
930 // if the definition of the variable member occurred in its
931 // namespace.
932 // Both of these imply that we should push a scope whose context
933 // is the semantic context of the declaration. We can't use
934 // PushDeclContext here because that context is not necessarily
935 // lexically contained in the current context. Fortunately,
936 // the containing scope should have the appropriate information.
937
938 assert(!S->getEntity() && "scope already has entity");
939
940#ifndef NDEBUG
941 Scope *Ancestor = S->getParent();
942 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
943 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
944#endif
945
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000946 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000947 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000948}
949
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000950void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000951 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000952
John McCall6df5fef2009-12-19 10:49:29 +0000953 // Switch back to the lexical context. The safety of this is
954 // enforced by an assert in EnterDeclaratorContext.
955 Scope *Ancestor = S->getParent();
956 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +0000957 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +0000958
959 // We don't need to do anything with the scope, which is going to
960 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000961}
962
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000963
964void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
965 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
966 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
967 // We assume that the caller has already called
968 // ActOnReenterTemplateScope
969 FD = TFD->getTemplatedDecl();
970 }
971 if (!FD)
972 return;
973
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000974 // Same implementation as PushDeclContext, but enters the context
975 // from the lexical parent, rather than the top-level class.
976 assert(CurContext == FD->getLexicalParent() &&
977 "The next DeclContext should be lexically contained in the current one.");
978 CurContext = FD;
979 S->setEntity(CurContext);
980
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000981 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
982 ParmVarDecl *Param = FD->getParamDecl(P);
983 // If the parameter has an identifier, then add it to the scope
984 if (Param->getIdentifier()) {
985 S->AddDecl(Param);
986 IdResolver.AddDecl(Param);
987 }
988 }
989}
990
991
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000992void Sema::ActOnExitFunctionContext() {
993 // Same implementation as PopDeclContext, but returns to the lexical parent,
994 // rather than the top-level class.
995 assert(CurContext && "DeclContext imbalance!");
996 CurContext = CurContext->getLexicalParent();
997 assert(CurContext && "Popped translation unit!");
998}
999
1000
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001001/// \brief Determine whether we allow overloading of the function
1002/// PrevDecl with another declaration.
1003///
1004/// This routine determines whether overloading is possible, not
1005/// whether some new function is actually an overload. It will return
1006/// true in C++ (where we can always provide overloads) or, as an
1007/// extension, in C when the previous function is already an
1008/// overloaded function declaration or has the "overloadable"
1009/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001010static bool AllowOverloadingOfFunction(LookupResult &Previous,
1011 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001012 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001013 return true;
1014
John McCall1f82f242009-11-18 22:49:29 +00001015 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001016 return true;
1017
John McCall1f82f242009-11-18 22:49:29 +00001018 return (Previous.getResultKind() == LookupResult::Found
1019 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001020}
1021
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001022/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001023void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001024 // Move up the scope chain until we find the nearest enclosing
1025 // non-transparent context. The declaration will be introduced into this
1026 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001027 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001028 S = S->getParent();
1029
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001030 // Add scoped declarations into their context, so that they can be
1031 // found later. Declarations without a context won't be inserted
1032 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001033 if (AddToContext)
1034 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001035
Richard Smith541b38b2013-09-20 01:15:31 +00001036 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1037 // are function-local declarations.
1038 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001039 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001040 D->getLexicalDeclContext()->getRedeclContext()) &&
1041 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001042 return;
1043
1044 // Template instantiations should also not be pushed into scope.
1045 if (isa<FunctionDecl>(D) &&
1046 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001047 return;
1048
John McCall9f3059a2009-10-09 21:13:30 +00001049 // If this replaces anything in the current scope,
1050 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1051 IEnd = IdResolver.end();
1052 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001053 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1054 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001055 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001056
John McCall9f3059a2009-10-09 21:13:30 +00001057 // Should only need to replace one decl.
1058 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001059 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001060 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061
John McCall48871652010-08-21 09:40:31 +00001062 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001063
1064 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1065 // Implicitly-generated labels may end up getting generated in an order that
1066 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1067 // the label at the appropriate place in the identifier chain.
1068 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001069 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001070 if (IDC == CurContext) {
1071 if (!S->isDeclScope(*I))
1072 continue;
1073 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001074 break;
1075 }
1076
Douglas Gregor46c04e72011-03-16 16:39:03 +00001077 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001078 } else {
1079 IdResolver.AddDecl(D);
1080 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001081}
1082
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001083void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1084 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1085 TUScope->AddDecl(D);
1086}
1087
Richard Smith1c34fb72013-08-13 18:18:50 +00001088bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001089 bool AllowInlineNamespace) {
1090 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001091}
1092
John McCallcc14d1f2010-08-24 08:50:51 +00001093Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1094 DeclContext *TargetDC = DC->getPrimaryContext();
1095 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001096 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001097 if (ScopeDC->getPrimaryContext() == TargetDC)
1098 return S;
1099 } while ((S = S->getParent()));
1100
1101 return 0;
1102}
1103
John McCall1f82f242009-11-18 22:49:29 +00001104static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1105 DeclContext*,
1106 ASTContext&);
1107
1108/// Filters out lookup results that don't fall within the given scope
1109/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001110void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001111 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001112 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001113 LookupResult::Filter F = R.makeFilter();
1114 while (F.hasNext()) {
1115 NamedDecl *D = F.next();
1116
Richard Smith72bcaec2013-12-05 04:30:04 +00001117 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001118 continue;
1119
Richard Smith72bcaec2013-12-05 04:30:04 +00001120 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001121 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001122
John McCall1f82f242009-11-18 22:49:29 +00001123 F.erase();
1124 }
1125
1126 F.done();
1127}
1128
1129static bool isUsingDecl(NamedDecl *D) {
1130 return isa<UsingShadowDecl>(D) ||
1131 isa<UnresolvedUsingTypenameDecl>(D) ||
1132 isa<UnresolvedUsingValueDecl>(D);
1133}
1134
1135/// Removes using shadow declarations from the lookup results.
1136static void RemoveUsingDecls(LookupResult &R) {
1137 LookupResult::Filter F = R.makeFilter();
1138 while (F.hasNext())
1139 if (isUsingDecl(F.next()))
1140 F.erase();
1141
1142 F.done();
1143}
1144
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001145/// \brief Check for this common pattern:
1146/// @code
1147/// class S {
1148/// S(const S&); // DO NOT IMPLEMENT
1149/// void operator=(const S&); // DO NOT IMPLEMENT
1150/// };
1151/// @endcode
1152static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1153 // FIXME: Should check for private access too but access is set after we get
1154 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001155 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001156 return false;
1157
1158 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1159 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001160 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1161 return Method->isCopyAssignmentOperator();
1162 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001163}
1164
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001165// We need this to handle
1166//
1167// typedef struct {
1168// void *foo() { return 0; }
1169// } A;
1170//
1171// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1172// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001173// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001174// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001175// Callers should verify at the end of the TU if it D has external linkage or
1176// not.
1177bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1178 const DeclContext *DC = D->getDeclContext();
1179 while (!DC->isTranslationUnit()) {
1180 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1181 if (!RD->hasNameForLinkage())
1182 return true;
1183 }
1184 DC = DC->getParent();
1185 }
1186
Rafael Espindola3ae00052013-05-13 00:12:11 +00001187 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001188}
1189
Eli Friedman5ef21752013-09-10 03:05:56 +00001190// FIXME: This needs to be refactored; some other isInMainFile users want
1191// these semantics.
1192static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1193 if (S.TUKind != TU_Complete)
1194 return false;
1195 return S.SourceMgr.isInMainFile(Loc);
1196}
1197
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001198bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1199 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001200
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001201 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1202 return false;
1203
1204 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001205 if (D->getDeclContext()->isDependentContext() ||
1206 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001207 return false;
1208
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001209 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001210 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1211 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001212
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001213 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1214 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1215 return false;
1216 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001217 // 'static inline' functions are defined in headers; don't warn.
1218 if (FD->isInlineSpecified() &&
1219 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001220 return false;
1221 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001222
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001223 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001224 Context.DeclMustBeEmitted(FD))
1225 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001226 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001227 // Constants and utility variables are defined in headers with internal
1228 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1229 // like "inline".)
1230 if (!isMainFileLoc(*this, VD->getLocation()))
1231 return false;
1232
Eli Friedman5ef21752013-09-10 03:05:56 +00001233 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001234 return false;
1235
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001236 if (VD->isStaticDataMember() &&
1237 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1238 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001239 } else {
1240 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001241 }
1242
John McCalld37d35b2010-10-27 01:41:35 +00001243 // Only warn for unused decls internal to the translation unit.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001244 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001245}
1246
1247void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001248 if (!D)
1249 return;
1250
1251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001252 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001253 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1254 return; // First should already be in the vector.
1255 }
1256
1257 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001258 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001259 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1260 return; // First should already be in the vector.
1261 }
1262
David Blaikie3d8edc22012-05-26 05:35:39 +00001263 if (ShouldWarnIfUnusedFileScopedDecl(D))
1264 UnusedFileScopedDecls.push_back(D);
1265}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001266
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001267static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001268 if (D->isInvalidDecl())
1269 return false;
1270
Eli Friedmanc09e0552012-01-13 23:41:25 +00001271 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001272 return false;
John McCall67da35c2010-02-04 22:26:26 +00001273
Chris Lattnercab02a62011-02-17 20:34:02 +00001274 if (isa<LabelDecl>(D))
1275 return true;
1276
John McCall67da35c2010-02-04 22:26:26 +00001277 // White-list anything that isn't a local variable.
1278 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1279 !D->getDeclContext()->isFunctionOrMethod())
1280 return false;
1281
1282 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001283 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001284
1285 // White-list anything with an __attribute__((unused)) type.
1286 QualType Ty = VD->getType();
1287
1288 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001289 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001290 if (TT->getDecl()->hasAttr<UnusedAttr>())
1291 return false;
1292 }
1293
Douglas Gregor14f232e2010-05-08 23:05:03 +00001294 // If we failed to complete the type for some reason, or if the type is
1295 // dependent, don't diagnose the variable.
1296 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001297 return false;
1298
John McCallcef15822010-03-31 02:47:45 +00001299 if (const TagType *TT = Ty->getAs<TagType>()) {
1300 const TagDecl *Tag = TT->getDecl();
1301 if (Tag->hasAttr<UnusedAttr>())
1302 return false;
1303
1304 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001305 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001306 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001307
1308 if (const Expr *Init = VD->getInit()) {
David Blaikiea9d4a932012-10-24 21:29:06 +00001309 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1310 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001311 const CXXConstructExpr *Construct =
1312 dyn_cast<CXXConstructExpr>(Init);
1313 if (Construct && !Construct->isElidable()) {
1314 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001315 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001316 return false;
1317 }
1318 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001319 }
1320 }
John McCallcef15822010-03-31 02:47:45 +00001321
1322 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001323 }
1324
John McCall67da35c2010-02-04 22:26:26 +00001325 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001326}
1327
Anna Zaks964f4c62011-07-28 20:52:06 +00001328static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1329 FixItHint &Hint) {
1330 if (isa<LabelDecl>(D)) {
1331 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001332 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001333 if (AfterColon.isInvalid())
1334 return;
1335 Hint = FixItHint::CreateRemoval(CharSourceRange::
1336 getCharRange(D->getLocStart(), AfterColon));
1337 }
1338 return;
1339}
1340
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001341/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1342/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001343void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001344 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001345 if (!ShouldDiagnoseUnusedDecl(D))
1346 return;
1347
Anna Zaks964f4c62011-07-28 20:52:06 +00001348 GenerateFixForUnusedDecl(D, Context, Hint);
1349
Chris Lattnercab02a62011-02-17 20:34:02 +00001350 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001351 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001352 DiagID = diag::warn_unused_exception_param;
1353 else if (isa<LabelDecl>(D))
1354 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001355 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001356 DiagID = diag::warn_unused_variable;
1357
Anna Zaks964f4c62011-07-28 20:52:06 +00001358 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001359}
1360
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001361static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1362 // Verify that we have no forward references left. If so, there was a goto
1363 // or address of a label taken, but no definition of it. Label fwd
1364 // definitions are indicated with a null substmt.
1365 if (L->getStmt() == 0)
1366 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1367}
1368
Steve Naroffc62adb62007-10-09 22:01:59 +00001369void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001370 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001371 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001372 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001373
Chris Lattner302b4be2006-11-19 02:31:38 +00001374 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1375 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001376 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001377 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001378
Douglas Gregor91f84212008-12-11 16:49:14 +00001379 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1380 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001381
Douglas Gregor91f84212008-12-11 16:49:14 +00001382 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001383
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001384 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001385 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001386 DiagnoseUnusedDecl(D);
1387
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001388 // If this was a forward reference to a label, verify it was defined.
1389 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1390 CheckPoppedLabel(LD, *this);
1391
Douglas Gregor91f84212008-12-11 16:49:14 +00001392 // Remove this name from our lexical scope.
1393 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001394 }
1395}
1396
James Molloy6f8780b2012-02-29 10:24:19 +00001397void Sema::ActOnStartFunctionDeclarator() {
1398 ++InFunctionDeclarator;
1399}
1400
1401void Sema::ActOnEndFunctionDeclarator() {
1402 assert(InFunctionDeclarator);
1403 --InFunctionDeclarator;
1404}
1405
Douglas Gregor1c283312010-08-11 12:19:30 +00001406/// \brief Look for an Objective-C class in the translation unit.
1407///
1408/// \param Id The name of the Objective-C class we're looking for. If
1409/// typo-correction fixes this name, the Id will be updated
1410/// to the fixed name.
1411///
1412/// \param IdLoc The location of the name in the translation unit.
1413///
James Dennett41725122012-06-22 10:16:05 +00001414/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001415/// if there is no class with the given name.
1416///
1417/// \returns The declaration of the named Objective-C class, or NULL if the
1418/// class could not be found.
1419ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1420 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001421 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001422 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1423 // creation from this context.
1424 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1425
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001426 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001427 // Perform typo correction at the given location, but only if we
1428 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001429 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1430 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1431 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001432 Validator)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001433 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001434 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001435 Id = IDecl->getIdentifier();
1436 }
1437 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001438 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1439 // This routine must always return a class definition, if any.
1440 if (Def && Def->getDefinition())
1441 Def = Def->getDefinition();
1442 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001443}
1444
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001445/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1446/// from S, where a non-field would be declared. This routine copes
1447/// with the difference between C and C++ scoping rules in structs and
1448/// unions. For example, the following code is well-formed in C but
1449/// ill-formed in C++:
1450/// @code
1451/// struct S6 {
1452/// enum { BAR } e;
1453/// };
Mike Stump11289f42009-09-09 15:08:12 +00001454///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001455/// void test_S6() {
1456/// struct S6 a;
1457/// a.e = BAR;
1458/// }
1459/// @endcode
1460/// For the declaration of BAR, this routine will return a different
1461/// scope. The scope S will be the scope of the unnamed enumeration
1462/// within S6. In C++, this routine will return the scope associated
1463/// with S6, because the enumeration's scope is a transparent
1464/// context but structures can contain non-field names. In C, this
1465/// routine will return the translation unit scope, since the
1466/// enumeration's scope is a transparent context and structures cannot
1467/// contain non-field names.
1468Scope *Sema::getNonFieldDeclScope(Scope *S) {
1469 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001470 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001471 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001472 S = S->getParent();
1473 return S;
1474}
1475
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001476/// \brief Looks up the declaration of "struct objc_super" and
1477/// saves it for later use in building builtin declaration of
1478/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1479/// pre-existing declaration exists no action takes place.
1480static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1481 IdentifierInfo *II) {
1482 if (!II->isStr("objc_msgSendSuper"))
1483 return;
1484 ASTContext &Context = ThisSema.Context;
1485
1486 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1487 SourceLocation(), Sema::LookupTagName);
1488 ThisSema.LookupName(Result, S);
1489 if (Result.getResultKind() == LookupResult::Found)
1490 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1491 Context.setObjCSuperType(Context.getTagDeclType(TD));
1492}
1493
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001494/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1495/// file scope. lazily create a decl for it. ForRedeclaration is true
1496/// if we're creating this built-in in anticipation of redeclaring the
1497/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001498NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001499 Scope *S, bool ForRedeclaration,
1500 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001501 LookupPredefedObjCSuperType(*this, S, II);
1502
Chris Lattner9561a0b2007-01-28 08:20:04 +00001503 Builtin::ID BID = (Builtin::ID)bid;
1504
Chris Lattnerecd79c62009-06-14 00:45:47 +00001505 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001506 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001507 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001508 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001509 // Okay
1510 break;
1511
Mike Stump93246cc2009-07-28 23:57:15 +00001512 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001513 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001514 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001515 << Context.BuiltinInfo.GetName(BID);
1516 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001517
Mike Stump93246cc2009-07-28 23:57:15 +00001518 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001519 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001520 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001521 << Context.BuiltinInfo.GetName(BID);
1522 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001523
1524 case ASTContext::GE_Missing_ucontext:
1525 if (ForRedeclaration)
1526 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1527 << Context.BuiltinInfo.GetName(BID);
1528 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001529 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001530
1531 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1532 Diag(Loc, diag::ext_implicit_lib_function_decl)
1533 << Context.BuiltinInfo.GetName(BID)
1534 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001535 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001536 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001537 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001538 Diag(Loc, diag::note_please_include_header)
1539 << Context.BuiltinInfo.getHeaderName(BID)
1540 << Context.BuiltinInfo.GetName(BID);
1541 }
1542
Warren Hunt445d83e2013-11-01 23:46:51 +00001543 DeclContext *Parent = Context.getTranslationUnitDecl();
1544 if (getLangOpts().CPlusPlus) {
1545 LinkageSpecDecl *CLinkageDecl =
1546 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1547 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001548 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001549 Parent->addDecl(CLinkageDecl);
1550 Parent = CLinkageDecl;
1551 }
1552
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001553 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001554 Parent,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001555 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001556 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001557 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001558 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001559 New->setImplicit();
1560
Chris Lattner4dd27102008-05-05 22:18:14 +00001561 // Create Decl objects for each parameter, adding them to the
1562 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001563 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001564 SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001565 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1566 ParmVarDecl *parm =
1567 ParmVarDecl::Create(Context, New, SourceLocation(),
1568 SourceLocation(), 0,
1569 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001570 SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001571 parm->setScopeInfo(0, i);
1572 Params.push_back(parm);
1573 }
David Blaikie9c70e042011-09-21 18:16:56 +00001574 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001575 }
Mike Stump11289f42009-09-09 15:08:12 +00001576
1577 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001578 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001579
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001580 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001581 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1582 // relate Scopes to DeclContexts, and probably eliminate CurContext
1583 // entirely, but we're not there yet.
1584 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001585 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001586 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001587 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001588 return New;
1589}
1590
Douglas Gregor3552dab2013-01-09 00:47:56 +00001591/// \brief Filter out any previous declarations that the given declaration
1592/// should not consider because they are not permitted to conflict, e.g.,
1593/// because they come from hidden sub-modules and do not refer to the same
1594/// entity.
1595static void filterNonConflictingPreviousDecls(ASTContext &context,
1596 NamedDecl *decl,
1597 LookupResult &previous){
1598 // This is only interesting when modules are enabled.
1599 if (!context.getLangOpts().Modules)
1600 return;
1601
1602 // Empty sets are uninteresting.
1603 if (previous.empty())
1604 return;
1605
Douglas Gregor3552dab2013-01-09 00:47:56 +00001606 LookupResult::Filter filter = previous.makeFilter();
1607 while (filter.hasNext()) {
1608 NamedDecl *old = filter.next();
1609
1610 // Non-hidden declarations are never ignored.
1611 if (!old->isHidden())
1612 continue;
1613
Rafael Espindola3ae00052013-05-13 00:12:11 +00001614 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001615 filter.erase();
1616 }
1617
1618 filter.done();
1619}
1620
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001621bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1622 QualType OldType;
1623 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1624 OldType = OldTypedef->getUnderlyingType();
1625 else
1626 OldType = Context.getTypeDeclType(Old);
1627 QualType NewType = New->getUnderlyingType();
1628
Douglas Gregoraab36982012-01-11 22:33:48 +00001629 if (NewType->isVariablyModifiedType()) {
1630 // Must not redefine a typedef with a variably-modified type.
1631 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1632 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1633 << Kind << NewType;
1634 if (Old->getLocation().isValid())
1635 Diag(Old->getLocation(), diag::note_previous_definition);
1636 New->setInvalidDecl();
1637 return true;
1638 }
1639
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001640 if (OldType != NewType &&
1641 !OldType->isDependentType() &&
1642 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001643 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001644 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1645 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1646 << Kind << NewType << OldType;
1647 if (Old->getLocation().isValid())
1648 Diag(Old->getLocation(), diag::note_previous_definition);
1649 New->setInvalidDecl();
1650 return true;
1651 }
1652 return false;
1653}
1654
Richard Smithdda56e42011-04-15 14:24:37 +00001655/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001656/// same name and scope as a previous declaration 'Old'. Figure out
1657/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001658/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001659///
Richard Smithdda56e42011-04-15 14:24:37 +00001660void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001661 // If the new decl is known invalid already, don't bother doing any
1662 // merging checks.
1663 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001664
Steve Naroff44cfcb62008-09-09 14:32:20 +00001665 // Allow multiple definitions for ObjC built-in typedefs.
1666 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001667 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001668 const IdentifierInfo *TypeID = New->getIdentifier();
1669 switch (TypeID->getLength()) {
1670 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001671 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001672 {
1673 if (!TypeID->isStr("id"))
1674 break;
1675 QualType T = New->getUnderlyingType();
1676 if (!T->isPointerType())
1677 break;
1678 if (!T->isVoidPointerType()) {
1679 QualType PT = T->getAs<PointerType>()->getPointeeType();
1680 if (!PT->isStructureType())
1681 break;
1682 }
1683 Context.setObjCIdRedefinitionType(T);
1684 // Install the built-in type for 'id', ignoring the current definition.
1685 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1686 return;
1687 }
Chris Lattner66e32812008-11-20 05:41:43 +00001688 case 5:
1689 if (!TypeID->isStr("Class"))
1690 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001691 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001692 // Install the built-in type for 'Class', ignoring the current definition.
1693 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001694 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001695 case 3:
1696 if (!TypeID->isStr("SEL"))
1697 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001698 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001699 // Install the built-in type for 'SEL', ignoring the current definition.
1700 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001701 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001702 }
1703 // Fall through - the typedef name was not a builtin type.
1704 }
John McCall1f82f242009-11-18 22:49:29 +00001705
Douglas Gregorfb034662009-01-28 17:15:10 +00001706 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001707 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1708 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001709 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001710 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001711
1712 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001713 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001714 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001715
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001716 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001717 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001718
John McCall1f82f242009-11-18 22:49:29 +00001719 // If the old declaration is invalid, just give up here.
1720 if (Old->isInvalidDecl())
1721 return New->setInvalidDecl();
1722
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001723 // If the typedef types are not identical, reject them in all languages and
1724 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001725 if (isIncompatibleTypedef(Old, New))
1726 return;
Mike Stump11289f42009-09-09 15:08:12 +00001727
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001728 // The types match. Link up the redeclaration chain and merge attributes if
1729 // the old declaration was a typedef.
1730 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001731 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001732 mergeDeclAttributes(New, Old);
1733 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001734
David Blaikiebbafb8a2012-03-11 07:00:24 +00001735 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001736 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001737
David Blaikiebbafb8a2012-03-11 07:00:24 +00001738 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001739 // C++ [dcl.typedef]p2:
1740 // In a given non-class scope, a typedef specifier can be used to
1741 // redefine the name of any type declared in that scope to refer
1742 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001743 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001744 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001745
1746 // C++0x [dcl.typedef]p4:
1747 // In a given class scope, a typedef specifier can be used to redefine
1748 // any class-name declared in that scope that is not also a typedef-name
1749 // to refer to the type to which it already refers.
1750 //
1751 // This wording came in via DR424, which was a correction to the
1752 // wording in DR56, which accidentally banned code like:
1753 //
1754 // struct S {
1755 // typedef struct A { } A;
1756 // };
1757 //
1758 // in the C++03 standard. We implement the C++0x semantics, which
1759 // allow the above but disallow
1760 //
1761 // struct S {
1762 // typedef int I;
1763 // typedef int I;
1764 // };
1765 //
1766 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001767 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001768 return;
1769
Chris Lattner2581fc32009-04-17 22:04:20 +00001770 Diag(New->getLocation(), diag::err_redefinition)
1771 << New->getDeclName();
1772 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001773 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001774 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001775
Douglas Gregor7363fb02012-01-11 04:25:01 +00001776 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001777 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001778 return;
1779
Chris Lattner2581fc32009-04-17 22:04:20 +00001780 // If we have a redefinition of a typedef in C, emit a warning. This warning
1781 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001782 // -Wtypedef-redefinition. If either the original or the redefinition is
1783 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001784 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001785 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1786 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001787 return;
Mike Stump11289f42009-09-09 15:08:12 +00001788
Chris Lattner2581fc32009-04-17 22:04:20 +00001789 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1790 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001791 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001792 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001793}
1794
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001795/// DeclhasAttr - returns true if decl Declaration already has the target
1796/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001797static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001798DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001799 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1800 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1801 // responsible for making sure they are consistent.
1802 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1803 if (AA)
1804 return false;
1805
DeLesley Hutchins2d0881b2012-10-12 21:38:12 +00001806 // The following thread safety attributes can also be duplicated.
1807 switch (A->getKind()) {
1808 case attr::ExclusiveLocksRequired:
1809 case attr::SharedLocksRequired:
1810 case attr::LocksExcluded:
1811 case attr::ExclusiveLockFunction:
1812 case attr::SharedLockFunction:
1813 case attr::UnlockFunction:
1814 case attr::ExclusiveTrylockFunction:
1815 case attr::SharedTrylockFunction:
1816 case attr::GuardedBy:
1817 case attr::PtGuardedBy:
1818 case attr::AcquiredBefore:
1819 case attr::AcquiredAfter:
1820 return false;
DeLesley Hutchins6c6e8592012-10-12 21:49:04 +00001821 default:
1822 ;
DeLesley Hutchins2d0881b2012-10-12 21:38:12 +00001823 }
1824
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001825 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001826 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001827 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1828 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001829 if (Ann) {
1830 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1831 return true;
1832 continue;
1833 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001834 // FIXME: Don't hardcode this check
1835 if (OA && isa<OwnershipAttr>(*i))
1836 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001837 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001838 }
Chris Lattner84966392008-03-03 03:28:21 +00001839
1840 return false;
1841}
1842
Richard Smithbc8caaf2013-02-22 04:55:39 +00001843static bool isAttributeTargetADefinition(Decl *D) {
1844 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1845 return VD->isThisDeclarationADefinition();
1846 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1847 return TD->isCompleteDefinition() || TD->isBeingDefined();
1848 return true;
1849}
1850
1851/// Merge alignment attributes from \p Old to \p New, taking into account the
1852/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1853///
1854/// \return \c true if any attributes were added to \p New.
1855static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1856 // Look for alignas attributes on Old, and pick out whichever attribute
1857 // specifies the strictest alignment requirement.
1858 AlignedAttr *OldAlignasAttr = 0;
1859 AlignedAttr *OldStrictestAlignAttr = 0;
1860 unsigned OldAlign = 0;
1861 for (specific_attr_iterator<AlignedAttr>
1862 I = Old->specific_attr_begin<AlignedAttr>(),
1863 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1864 // FIXME: We have no way of representing inherited dependent alignments
1865 // in a case like:
1866 // template<int A, int B> struct alignas(A) X;
1867 // template<int A, int B> struct alignas(B) X {};
1868 // For now, we just ignore any alignas attributes which are not on the
1869 // definition in such a case.
1870 if (I->isAlignmentDependent())
1871 return false;
1872
1873 if (I->isAlignas())
1874 OldAlignasAttr = *I;
1875
1876 unsigned Align = I->getAlignment(S.Context);
1877 if (Align > OldAlign) {
1878 OldAlign = Align;
1879 OldStrictestAlignAttr = *I;
1880 }
1881 }
1882
1883 // Look for alignas attributes on New.
1884 AlignedAttr *NewAlignasAttr = 0;
1885 unsigned NewAlign = 0;
1886 for (specific_attr_iterator<AlignedAttr>
1887 I = New->specific_attr_begin<AlignedAttr>(),
1888 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1889 if (I->isAlignmentDependent())
1890 return false;
1891
1892 if (I->isAlignas())
1893 NewAlignasAttr = *I;
1894
1895 unsigned Align = I->getAlignment(S.Context);
1896 if (Align > NewAlign)
1897 NewAlign = Align;
1898 }
1899
1900 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1901 // Both declarations have 'alignas' attributes. We require them to match.
1902 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1903 // fall short. (If two declarations both have alignas, they must both match
1904 // every definition, and so must match each other if there is a definition.)
1905
1906 // If either declaration only contains 'alignas(0)' specifiers, then it
1907 // specifies the natural alignment for the type.
1908 if (OldAlign == 0 || NewAlign == 0) {
1909 QualType Ty;
1910 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1911 Ty = VD->getType();
1912 else
1913 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1914
1915 if (OldAlign == 0)
1916 OldAlign = S.Context.getTypeAlign(Ty);
1917 if (NewAlign == 0)
1918 NewAlign = S.Context.getTypeAlign(Ty);
1919 }
1920
1921 if (OldAlign != NewAlign) {
1922 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1923 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1924 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1925 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1926 }
1927 }
1928
1929 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1930 // C++11 [dcl.align]p6:
1931 // if any declaration of an entity has an alignment-specifier,
1932 // every defining declaration of that entity shall specify an
1933 // equivalent alignment.
1934 // C11 6.7.5/7:
1935 // If the definition of an object does not have an alignment
1936 // specifier, any other declaration of that object shall also
1937 // have no alignment specifier.
1938 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001939 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001940 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001941 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001942 }
1943
1944 bool AnyAdded = false;
1945
1946 // Ensure we have an attribute representing the strictest alignment.
1947 if (OldAlign > NewAlign) {
1948 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1949 Clone->setInherited(true);
1950 New->addAttr(Clone);
1951 AnyAdded = true;
1952 }
1953
1954 // Ensure we have an alignas attribute if the old declaration had one.
1955 if (OldAlignasAttr && !NewAlignasAttr &&
1956 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1957 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1958 Clone->setInherited(true);
1959 New->addAttr(Clone);
1960 AnyAdded = true;
1961 }
1962
1963 return AnyAdded;
1964}
1965
1966static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1967 bool Override) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001968 InheritableAttr *NewAttr = NULL;
Michael Han99315932013-01-24 16:46:58 +00001969 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola19de5612013-01-12 06:42:30 +00001970 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001971 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1972 AA->getIntroduced(), AA->getDeprecated(),
1973 AA->getObsoleted(), AA->getUnavailable(),
1974 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001975 AttrSpellingListIndex);
Richard Smithbc8caaf2013-02-22 04:55:39 +00001976 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1977 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1978 AttrSpellingListIndex);
1979 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1980 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1981 AttrSpellingListIndex);
Rafael Espindola19de5612013-01-12 06:42:30 +00001982 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001983 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1984 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001985 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001986 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1987 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001988 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001989 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1990 FA->getFormatIdx(), FA->getFirstArg(),
1991 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001992 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001993 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1994 AttrSpellingListIndex);
1995 else if (isa<AlignedAttr>(Attr))
1996 // AlignedAttrs are handled separately, because we need to handle all
1997 // such attributes on a declaration at the same time.
1998 NewAttr = 0;
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001999 else if (!DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002000 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00002001
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002002 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002003 NewAttr->setInherited(true);
2004 D->addAttr(NewAttr);
2005 return true;
2006 }
2007
2008 return false;
2009}
2010
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002011static const Decl *getDefinition(const Decl *D) {
2012 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00002013 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002014 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2015 const VarDecl *Def = VD->getDefinition();
2016 if (Def)
2017 return Def;
2018 return VD->getActingDefinition();
2019 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002020 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00002021 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002022 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00002023 return Def;
2024 }
2025 return NULL;
2026}
2027
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002028static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2029 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2030 I != E; ++I) {
2031 Attr *Attribute = *I;
2032 if (Attribute->getKind() == Kind)
2033 return true;
2034 }
2035 return false;
2036}
2037
2038/// checkNewAttributesAfterDef - If we already have a definition, check that
2039/// there are no new attributes in this declaration.
2040static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2041 if (!New->hasAttrs())
2042 return;
2043
2044 const Decl *Def = getDefinition(Old);
2045 if (!Def || Def == New)
2046 return;
2047
2048 AttrVec &NewAttributes = New->getAttrs();
2049 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2050 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002051
2052 if (isa<AliasAttr>(NewAttribute)) {
2053 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2054 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2055 else {
2056 VarDecl *VD = cast<VarDecl>(New);
2057 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2058 VarDecl::TentativeDefinition
2059 ? diag::err_alias_after_tentative
2060 : diag::err_redefinition;
2061 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2062 S.Diag(Def->getLocation(), diag::note_previous_definition);
2063 VD->setInvalidDecl();
2064 }
2065 ++I;
2066 continue;
2067 }
2068
2069 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2070 // Tentative definitions are only interesting for the alias check above.
2071 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2072 ++I;
2073 continue;
2074 }
2075 }
2076
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002077 if (hasAttribute(Def, NewAttribute->getKind())) {
2078 ++I;
2079 continue; // regular attr merging will take care of validating this.
2080 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002081
Richard Smithdebc59d2013-01-30 05:45:05 +00002082 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002083 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002084 ++I;
2085 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002086 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2087 if (AA->isAlignas()) {
2088 // C++11 [dcl.align]p6:
2089 // if any declaration of an entity has an alignment-specifier,
2090 // every defining declaration of that entity shall specify an
2091 // equivalent alignment.
2092 // C11 6.7.5/7:
2093 // If the definition of an object does not have an alignment
2094 // specifier, any other declaration of that object shall also
2095 // have no alignment specifier.
2096 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002097 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002098 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002099 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002100 NewAttributes.erase(NewAttributes.begin() + I);
2101 --E;
2102 continue;
2103 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002104 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002105
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002106 S.Diag(NewAttribute->getLocation(),
2107 diag::warn_attribute_precede_definition);
2108 S.Diag(Def->getLocation(), diag::note_previous_definition);
2109 NewAttributes.erase(NewAttributes.begin() + I);
2110 --E;
2111 }
2112}
2113
John McCallf79e87d2011-03-02 04:00:57 +00002114/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002115void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002116 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002117 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2118 UsedAttr *NewAttr = OldAttr->clone(Context);
2119 NewAttr->setInherited(true);
2120 New->addAttr(NewAttr);
2121 }
2122
Richard Smithe233fbf2013-01-28 22:42:45 +00002123 if (!Old->hasAttrs() && !New->hasAttrs())
2124 return;
2125
Rafael Espindola36191042012-05-18 01:47:00 +00002126 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002127 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002128
Douglas Gregor32c17572012-01-01 20:30:41 +00002129 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002130 return;
John McCallf79e87d2011-03-02 04:00:57 +00002131
Douglas Gregor32c17572012-01-01 20:30:41 +00002132 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002133
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002134 // Ensure that any moving of objects within the allocated map is done before
2135 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002136 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002137
Peter Collingbourneab8bc062011-01-21 02:08:36 +00002138 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor32c17572012-01-01 20:30:41 +00002139 i = Old->specific_attr_begin<InheritableAttr>(),
2140 e = Old->specific_attr_end<InheritableAttr>();
2141 i != e; ++i) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002142 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002143 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002144 if (isa<DeprecatedAttr>(*i) ||
2145 isa<UnavailableAttr>(*i) ||
2146 isa<AvailabilityAttr>(*i)) {
2147 switch (AMK) {
2148 case AMK_None:
2149 continue;
John McCalld2930c22011-07-22 02:45:48 +00002150
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002151 case AMK_Redeclaration:
2152 break;
2153
2154 case AMK_Override:
2155 Override = true;
2156 break;
2157 }
2158 }
2159
Rafael Espindolab0938852013-10-25 01:28:12 +00002160 // Already handled.
2161 if (isa<UsedAttr>(*i))
2162 continue;
2163
Richard Smithbc8caaf2013-02-22 04:55:39 +00002164 if (mergeDeclAttribute(*this, New, *i, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002165 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002166 }
John McCallf79e87d2011-03-02 04:00:57 +00002167
Richard Smithbc8caaf2013-02-22 04:55:39 +00002168 if (mergeAlignedAttrs(*this, New, Old))
2169 foundAny = true;
2170
Douglas Gregor32c17572012-01-01 20:30:41 +00002171 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002172}
2173
2174/// mergeParamDeclAttributes - Copy attributes from the old parameter
2175/// to the new one.
2176static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2177 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002178 Sema &S) {
2179 // C++11 [dcl.attr.depend]p2:
2180 // The first declaration of a function shall specify the
2181 // carries_dependency attribute for its declarator-id if any declaration
2182 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002183 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2184 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2185 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002186 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2187 // Find the first declaration of the parameter.
2188 // FIXME: Should we build redeclaration chains for function parameters?
2189 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002190 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002191 const ParmVarDecl *FirstVD =
2192 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2193 S.Diag(FirstVD->getLocation(),
2194 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2195 }
2196
John McCallf79e87d2011-03-02 04:00:57 +00002197 if (!oldDecl->hasAttrs())
2198 return;
2199
2200 bool foundAny = newDecl->hasAttrs();
2201
2202 // Ensure that any moving of objects within the allocated map is
2203 // done before we process them.
2204 if (!foundAny) newDecl->setAttrs(AttrVec());
2205
2206 for (specific_attr_iterator<InheritableParamAttr>
2207 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2208 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2209 if (!DeclHasAttr(newDecl, *i)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002210 InheritableAttr *newAttr =
2211 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002212 newAttr->setInherited(true);
2213 newDecl->addAttr(newAttr);
2214 foundAny = true;
2215 }
2216 }
2217
2218 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002219}
2220
Dan Gohman28ade552010-07-26 21:25:24 +00002221namespace {
2222
Douglas Gregora74a2972009-03-06 22:43:54 +00002223/// Used in MergeFunctionDecl to keep track of function parameters in
2224/// C.
2225struct GNUCompatibleParamWarning {
2226 ParmVarDecl *OldParm;
2227 ParmVarDecl *NewParm;
2228 QualType PromotedType;
2229};
2230
Dan Gohman28ade552010-07-26 21:25:24 +00002231}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002232
2233/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002234Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002235 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002236 if (Ctor->isDefaultConstructor())
2237 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002238
2239 if (Ctor->isCopyConstructor())
2240 return Sema::CXXCopyConstructor;
2241
2242 if (Ctor->isMoveConstructor())
2243 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002244 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002245 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002246 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002247 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002248 } else if (MD->isMoveAssignmentOperator()) {
2249 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002250 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002251
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002252 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002253}
2254
Sebastian Redl243d9052010-06-09 21:17:41 +00002255/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002256/// only extern inline functions can be redefined, and even then only in
2257/// GNU89 mode.
2258static bool canRedefineFunction(const FunctionDecl *FD,
2259 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002260 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2261 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002262 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002263 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002264}
2265
Reid Kleckner78af0702013-08-27 23:08:25 +00002266const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2267 const AttributedType *AT = T->getAs<AttributedType>();
2268 while (AT && !AT->isCallingConv())
2269 AT = AT->getModifiedType()->getAs<AttributedType>();
2270 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002271}
2272
Benjamin Kramer3e350262013-02-15 12:30:38 +00002273template <typename T>
2274static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002275 const DeclContext *DC = Old->getDeclContext();
2276 if (DC->isRecord())
2277 return false;
2278
2279 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002280 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002281 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002282 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002283 return true;
2284 return false;
2285}
2286
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002287/// MergeFunctionDecl - We just parsed a function 'New' from
2288/// declarator D which has the same name and scope as a previous
2289/// declaration 'Old'. Figure out how to resolve this situation,
2290/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002291///
2292/// In C++, New and Old must be declarations that are not
2293/// overloaded. Use IsOverload to determine whether New and Old are
2294/// overloaded, and to select the Old declaration that New should be
2295/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002296///
2297/// Returns true if there was an error, false otherwise.
Richard Smith1c34fb72013-08-13 18:18:50 +00002298bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2299 bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002300 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002301 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002302 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002303 = dyn_cast<FunctionTemplateDecl>(OldD))
2304 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002305 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002306 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00002307 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002308 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002309 if (New->getFriendObjectKind()) {
2310 Diag(New->getLocation(), diag::err_using_decl_friend);
2311 Diag(Shadow->getTargetDecl()->getLocation(),
2312 diag::note_using_decl_target);
2313 Diag(Shadow->getUsingDecl()->getLocation(),
2314 diag::note_using_decl) << 0;
2315 return true;
2316 }
2317
John McCalle29c5cd2009-12-10 19:51:03 +00002318 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2319 Diag(Shadow->getTargetDecl()->getLocation(),
2320 diag::note_using_decl_target);
2321 Diag(Shadow->getUsingDecl()->getLocation(),
2322 diag::note_using_decl) << 0;
2323 return true;
2324 }
2325
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002326 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002327 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002328 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002329 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00002330 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002331
David Majnemerea5092a2013-07-07 23:49:50 +00002332 // If the old declaration is invalid, just give up here.
2333 if (Old->isInvalidDecl())
2334 return true;
2335
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002336 // Determine whether the previous declaration was a definition,
2337 // implicit declaration, or a declaration.
2338 diag::kind PrevDiag;
2339 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002340 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002341 else if (Old->isImplicit())
2342 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002343 else
Chris Lattner0369c572008-11-23 23:12:31 +00002344 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002345
Charles Davisfea48452010-02-18 02:00:42 +00002346 // Don't complain about this if we're in GNU89 mode and the old function
2347 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002348 // Don't complain about specializations. They are not supposed to have
2349 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002350 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002351 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002352 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002353 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002354 !canRedefineFunction(Old, getLangOpts())) {
2355 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002356 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2357 Diag(Old->getLocation(), PrevDiag);
2358 } else {
2359 Diag(New->getLocation(), diag::err_static_non_static) << New;
2360 Diag(Old->getLocation(), PrevDiag);
2361 return true;
2362 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002363 }
2364
Reid Kleckner78af0702013-08-27 23:08:25 +00002365
2366 // If a function is first declared with a calling convention, but is later
2367 // declared or defined without one, all following decls assume the calling
2368 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002369 //
John McCalla5f46fb2012-08-25 02:00:03 +00002370 // It's OK if a function is first declared without a calling convention,
2371 // but is later declared or defined with the default calling convention.
2372 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002373 // To test if either decl has an explicit calling convention, we look for
2374 // AttributedType sugar nodes on the type as written. If they are missing or
2375 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002376 //
2377 // Note also that we DO NOT return at this point, because we still have
2378 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002379 QualType OldQType = Context.getCanonicalType(Old->getType());
2380 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002381 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002382 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002383 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2384 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2385 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002386
Reid Kleckner78af0702013-08-27 23:08:25 +00002387 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002388 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002389 const FunctionType *FT =
2390 First->getType().getCanonicalType()->castAs<FunctionType>();
2391 FunctionType::ExtInfo FI = FT->getExtInfo();
2392 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2393 if (!NewCCExplicit) {
2394 // Inherit the CC from the previous declaration if it was specified
2395 // there but not here.
2396 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2397 RequiresAdjustment = true;
2398 } else {
2399 // Calling conventions aren't compatible, so complain.
2400 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2401 Diag(New->getLocation(), diag::err_cconv_change)
2402 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2403 << !FirstCCExplicit
2404 << (!FirstCCExplicit ? "" :
2405 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002406
Reid Kleckner78af0702013-08-27 23:08:25 +00002407 // Put the note on the first decl, since it is the one that matters.
2408 Diag(First->getLocation(), diag::note_previous_declaration);
2409 return true;
2410 }
John McCallcddbad02010-02-04 05:44:44 +00002411 }
2412
John McCallab26cfa2010-02-05 21:31:56 +00002413 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002414 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2415 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2416 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002417 }
2418
Douglas Gregor77e274f2010-06-18 21:30:25 +00002419 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002420 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2421 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2422 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002423 Diag(New->getLocation(), diag::err_regparm_mismatch)
2424 << NewType->getRegParmType()
2425 << OldType->getRegParmType();
2426 Diag(Old->getLocation(), diag::note_previous_declaration);
2427 return true;
2428 }
John McCall4f5019e2010-12-19 02:44:49 +00002429
2430 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2431 RequiresAdjustment = true;
2432 }
2433
Douglas Gregorf1404d72011-10-14 15:55:40 +00002434 // Merge ns_returns_retained attribute.
2435 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2436 if (NewTypeInfo.getProducesResult()) {
2437 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2438 Diag(Old->getLocation(), diag::note_previous_declaration);
2439 return true;
2440 }
2441
2442 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2443 RequiresAdjustment = true;
2444 }
2445
John McCall4f5019e2010-12-19 02:44:49 +00002446 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002447 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2448 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2449 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002450 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002451 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002452 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002453
2454 // If this redeclaration makes the function inline, we may need to add it to
2455 // UndefinedButUsed.
2456 if (!Old->isInlined() && New->isInlined() &&
2457 !New->hasAttr<GNUInlineAttr>() &&
2458 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2459 Old->isUsed(false) &&
2460 !Old->isDefined() && !New->isThisDeclarationADefinition())
2461 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2462 SourceLocation()));
2463
2464 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2465 // about it.
2466 if (New->hasAttr<GNUInlineAttr>() &&
2467 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2468 UndefinedButUsed.erase(Old->getCanonicalDecl());
2469 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002470
David Blaikiebbafb8a2012-03-11 07:00:24 +00002471 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002472 // (C++98 13.1p2):
2473 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002474 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002475 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002476
2477 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002478 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002479 // Redeclarations or specializations of a function or function template
2480 // with a declared return type that uses a placeholder type shall also
2481 // use that placeholder, not a deduced type.
2482 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2483 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2484 : OldType)->getResultType();
2485 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2486 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2487 : NewType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002488 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002489 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2490 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2491 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002492 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2493 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002494 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2495 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002496 if (New->isCXXClassMember() && New->isOutOfLine())
2497 Diag(New->getLocation(),
2498 diag::err_member_def_does_not_match_ret_type) << New;
2499 else
2500 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002501 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2502 return true;
2503 }
2504 else
2505 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002506 }
2507
Richard Smith2a7d4812013-05-04 07:00:32 +00002508 QualType OldReturnType = OldType->getResultType();
2509 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2510 if (OldReturnType != NewReturnType) {
2511 // If this function has a deduced return type and has already been
2512 // defined, copy the deduced value from the old declaration.
2513 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2514 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002515 New->setType(
2516 SubstAutoType(New->getType(),
2517 OldAT->isDependentType() ? Context.DependentTy
2518 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002519 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002520 SubstAutoType(NewQType,
2521 OldAT->isDependentType() ? Context.DependentTy
2522 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002523 }
2524 }
2525
2526 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2527 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002528 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002529 // Preserve triviality.
2530 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002531
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002532 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002533 // 2 CXXMethodDecls referring to the same function will be injected.
2534 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002535 bool IsClassScopeExplicitSpecialization =
2536 OldMethod->isFunctionTemplateSpecialization() &&
2537 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002538 bool isFriend = NewMethod->getFriendObjectKind();
2539
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002540 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2541 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002542 // -- Member function declarations with the same name and the
2543 // same parameter types cannot be overloaded if any of them
2544 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002545 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002546 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2547 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2548 return true;
2549 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002550
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002551 // C++ [class.mem]p1:
2552 // [...] A member shall not be declared twice in the
2553 // member-specification, except that a nested class or member
2554 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002555 if (ActiveTemplateInstantiations.empty()) {
2556 unsigned NewDiag;
2557 if (isa<CXXConstructorDecl>(OldMethod))
2558 NewDiag = diag::err_constructor_redeclared;
2559 else if (isa<CXXDestructorDecl>(NewMethod))
2560 NewDiag = diag::err_destructor_redeclared;
2561 else if (isa<CXXConversionDecl>(NewMethod))
2562 NewDiag = diag::err_conv_function_redeclared;
2563 else
2564 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002565
Richard Smith57e7ff92012-07-13 04:12:04 +00002566 Diag(New->getLocation(), NewDiag);
2567 } else {
2568 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2569 << New << New->getType();
2570 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002571 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002572
2573 // Complain if this is an explicit declaration of a special
2574 // member that was initially declared implicitly.
2575 //
2576 // As an exception, it's okay to befriend such methods in order
2577 // to permit the implicit constructor/destructor/operator calls.
2578 } else if (OldMethod->isImplicit()) {
2579 if (isFriend) {
2580 NewMethod->setImplicit();
2581 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002582 Diag(NewMethod->getLocation(),
2583 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002584 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002585 return true;
2586 }
Richard Smith337a5a12012-06-08 01:30:54 +00002587 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002588 Diag(NewMethod->getLocation(),
2589 diag::err_definition_of_explicitly_defaulted_member)
2590 << getSpecialMember(OldMethod);
2591 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002592 }
2593 }
2594
Richard Smith10876ef2013-01-17 01:30:42 +00002595 // C++11 [dcl.attr.noreturn]p1:
2596 // The first declaration of a function shall specify the noreturn
2597 // attribute if any declaration of that function specifies the noreturn
2598 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002599 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2600 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2601 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002602 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002603 diag::note_noreturn_missing_first_decl);
2604 }
2605
Richard Smithe233fbf2013-01-28 22:42:45 +00002606 // C++11 [dcl.attr.depend]p2:
2607 // The first declaration of a function shall specify the
2608 // carries_dependency attribute for its declarator-id if any declaration
2609 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002610 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2611 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2612 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002613 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002614 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002615 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2616 }
2617
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002618 // (C++98 8.3.5p3):
2619 // All declarations for a function shall agree exactly in both the
2620 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002621 // We also want to respect all the extended bits except noreturn.
2622
2623 // noreturn should now match unless the old type info didn't have it.
2624 QualType OldQTypeForComparison = OldQType;
2625 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2626 assert(OldQType == QualType(OldType, 0));
2627 const FunctionType *OldTypeForComparison
2628 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2629 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2630 assert(OldQTypeForComparison.isCanonical());
2631 }
2632
Rafael Espindolaf4187652013-02-14 01:18:37 +00002633 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002634 // As a special case, retain the language linkage from previous
2635 // declarations of a friend function as an extension.
2636 //
2637 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2638 // and is useful because there's otherwise no way to specify language
2639 // linkage within class scope.
2640 //
2641 // Check cautiously as the friend object kind isn't yet complete.
2642 if (New->getFriendObjectKind() != Decl::FOK_None) {
2643 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2644 Diag(Old->getLocation(), PrevDiag);
2645 } else {
2646 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2647 Diag(Old->getLocation(), PrevDiag);
2648 return true;
2649 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002650 }
2651
John McCall4f5019e2010-12-19 02:44:49 +00002652 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002653 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002654
Richard Smith541b38b2013-09-20 01:15:31 +00002655 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2656 New->isLocalExternDecl()) {
2657 // It's OK if we couldn't merge types for a local function declaraton
2658 // if either the old or new type is dependent. We'll merge the types
2659 // when we instantiate the function.
2660 return false;
2661 }
2662
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002663 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002664 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002665
2666 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002667 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002668 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002669 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002670 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2671 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002672 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002673 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002674 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002675 // The old declaration provided a function prototype, but the
2676 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002677 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002678 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002679 OldProto->arg_type_end());
2680 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002681 ParamTypes,
John McCalldb40c7f2010-12-14 08:05:40 +00002682 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002683 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002684 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002685
2686 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002687 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00002688 for (FunctionProtoType::arg_type_iterator
2689 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002690 ParamEnd = OldProto->arg_type_end();
2691 ParamType != ParamEnd; ++ParamType) {
2692 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002693 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002694 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002695 *ParamType, /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002696 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002697 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002698 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002699 Param->setImplicit();
2700 Params.push_back(Param);
2701 }
2702
David Blaikie9c70e042011-09-21 18:16:56 +00002703 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002704 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002705
Richard Smith1c34fb72013-08-13 18:18:50 +00002706 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002707 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002708
Douglas Gregora74a2972009-03-06 22:43:54 +00002709 // GNU C permits a K&R definition to follow a prototype declaration
2710 // if the declared types of the parameters in the K&R definition
2711 // match the types in the prototype declaration, even when the
2712 // promoted types of the parameters from the K&R definition differ
2713 // from the types in the prototype. GCC then keeps the types from
2714 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002715 //
2716 // If a variadic prototype is followed by a non-variadic K&R definition,
2717 // the K&R definition becomes variadic. This is sort of an edge case, but
2718 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2719 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002720 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002721 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002722 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002723 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002724 SmallVector<QualType, 16> ArgTypes;
2725 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002726 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002727 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002728 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002729 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002730
Douglas Gregora74a2972009-03-06 22:43:54 +00002731 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002732 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2733 NewProto->getResultType());
2734 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002735 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002736 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002737 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2738 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002739 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00002740 NewProto->getArgType(Idx))) {
2741 ArgTypes.push_back(NewParm->getType());
2742 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002743 NewParm->getType(),
2744 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00002745 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00002746 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2747 Warnings.push_back(Warn);
2748 ArgTypes.push_back(NewParm->getType());
2749 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002750 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002751 }
2752
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002753 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002754 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2755 Diag(Warnings[Warn].NewParm->getLocation(),
2756 diag::ext_param_promoted_not_compatible_with_prototype)
2757 << Warnings[Warn].PromotedType
2758 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002759 if (Warnings[Warn].OldParm->getLocation().isValid())
2760 Diag(Warnings[Warn].OldParm->getLocation(),
2761 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002762 }
2763
Richard Smith1c34fb72013-08-13 18:18:50 +00002764 if (MergeTypeWithOld)
2765 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2766 OldProto->getExtProtoInfo()));
2767 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002768 }
2769
2770 // Fall through to diagnose conflicting types.
2771 }
2772
John McCallad327cd2013-04-14 08:50:55 +00002773 // A function that has already been declared has been redeclared or
2774 // defined with a different type; show an appropriate diagnostic.
2775
2776 // If the previous declaration was an implicitly-generated builtin
2777 // declaration, then at the very least we should use a specialized note.
2778 unsigned BuiltinID;
2779 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2780 // If it's actually a library-defined builtin function like 'malloc'
2781 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002782 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002783 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2784 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2785 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002786
2787 // If this is a global redeclaration, just forget hereafter
2788 // about the "builtin-ness" of the function.
2789 //
2790 // Doing this for local extern declarations is problematic. If
2791 // the builtin declaration remains visible, a second invalid
2792 // local declaration will produce a hard error; if it doesn't
2793 // remain visible, a single bogus local redeclaration (which is
2794 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002795 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002796 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2797
Douglas Gregor893c2c92009-03-23 17:47:24 +00002798 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002799 }
Steve Naroff17832a42008-01-16 15:01:34 +00002800
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002801 PrevDiag = diag::note_previous_builtin_declaration;
2802 }
2803
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002804 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002805 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002806 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002807}
2808
Douglas Gregore62c0a42009-02-24 01:23:02 +00002809/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002810/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002811///
2812/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002813/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002814/// the new declaration, once we know that New is in fact a
2815/// redeclaration of Old.
2816///
2817/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002818bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002819 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002820 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002821 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002822
Douglas Gregore62c0a42009-02-24 01:23:02 +00002823 // Merge "pure" flag.
2824 if (Old->isPure())
2825 New->setPure();
2826
Rafael Espindolabefe1302012-11-25 14:07:59 +00002827 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002828 if (Old->getMostRecentDecl()->isUsed(false))
2829 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002830
John McCallf79e87d2011-03-02 04:00:57 +00002831 // Merge attributes from the parameters. These can mismatch with K&R
2832 // declarations.
2833 if (New->getNumParams() == Old->getNumParams())
2834 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2835 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002836 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002837
David Blaikiebbafb8a2012-03-11 07:00:24 +00002838 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002839 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002840
Rafael Espindola8778c282012-11-29 16:09:03 +00002841 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002842 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2843 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002844 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002845 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002846 New->setType(Merged);
2847
Douglas Gregore62c0a42009-02-24 01:23:02 +00002848 return false;
2849}
2850
John McCall31168b02011-06-15 23:02:42 +00002851
John McCallf79e87d2011-03-02 04:00:57 +00002852void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002853 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002854
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002855 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002856 AvailabilityMergeKind MergeKind =
2857 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2858 : AMK_Override;
2859 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002860
2861 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002862 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2863 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002864 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002865 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002866 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002867 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002868
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002869 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002870}
2871
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002872/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2873/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002874/// emitting diagnostics as appropriate.
2875///
2876/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002877/// to here in AddInitializerToDecl. We can't check them before the initializer
2878/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002879void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2880 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002881 if (New->isInvalidDecl() || Old->isInvalidDecl())
2882 return;
2883
2884 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002885 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002886 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002887 // We don't know what the new type is until the initializer is attached.
2888 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002889 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2890 // These could still be something that needs exception specs checked.
2891 return MergeVarDeclExceptionSpecs(New, Old);
2892 }
Richard Smith30482bc2011-02-20 03:19:35 +00002893 // C++ [basic.link]p10:
2894 // [...] the types specified by all declarations referring to a given
2895 // object or function shall be identical, except that declarations for an
2896 // array object can specify array types that differ by the presence or
2897 // absence of a major array bound (8.3.4).
2898 else if (Old->getType()->isIncompleteArrayType() &&
2899 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002900 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2901 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2902 if (Context.hasSameType(OldArray->getElementType(),
2903 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002904 MergedT = New->getType();
2905 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002906 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002907 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2908 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2909 if (Context.hasSameType(OldArray->getElementType(),
2910 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002911 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002912 } else if (New->getType()->isObjCObjectPointerType() &&
2913 Old->getType()->isObjCObjectPointerType()) {
2914 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2915 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002916 }
2917 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002918 // C 6.2.7p2:
2919 // All declarations that refer to the same object or function shall have
2920 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002921 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2922 }
2923 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002924 // It's OK if we couldn't merge types if either type is dependent, for a
2925 // block-scope variable. In other cases (static data members of class
2926 // templates, variable templates, ...), we require the types to be
2927 // equivalent.
2928 // FIXME: The C++ standard doesn't say anything about this.
2929 if ((New->getType()->isDependentType() ||
2930 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2931 // If the old type was dependent, we can't merge with it, so the new type
2932 // becomes dependent for now. We'll reproduce the original type when we
2933 // instantiate the TypeSourceInfo for the variable.
2934 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2935 New->setType(Context.DependentTy);
2936 return;
2937 }
2938
2939 // FIXME: Even if this merging succeeds, some other non-visible declaration
2940 // of this variable might have an incompatible type. For instance:
2941 //
2942 // extern int arr[];
2943 // void f() { extern int arr[2]; }
2944 // void g() { extern int arr[3]; }
2945 //
2946 // Neither C nor C++ requires a diagnostic for this, but we should still try
2947 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002948 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002949 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002950 Diag(Old->getLocation(), diag::note_previous_definition);
2951 return New->setInvalidDecl();
2952 }
John McCallb65e8fe2013-04-01 18:34:28 +00002953
2954 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002955 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002956 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002957 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002958}
2959
Richard Smith3c785782013-09-03 21:00:58 +00002960static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2961 LookupResult &Previous) {
2962 // C11 6.2.7p4:
2963 // For an identifier with internal or external linkage declared
2964 // in a scope in which a prior declaration of that identifier is
2965 // visible, if the prior declaration specifies internal or
2966 // external linkage, the type of the identifier at the later
2967 // declaration becomes the composite type.
2968 //
2969 // If the variable isn't visible, we do not merge with its type.
2970 if (Previous.isShadowed())
2971 return false;
2972
2973 if (S.getLangOpts().CPlusPlus) {
2974 // C++11 [dcl.array]p3:
2975 // If there is a preceding declaration of the entity in the same
2976 // scope in which the bound was specified, an omitted array bound
2977 // is taken to be the same as in that earlier declaration.
2978 return NewVD->isPreviousDeclInSameBlockScope() ||
2979 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2980 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2981 } else {
2982 // If the old declaration was function-local, don't merge with its
2983 // type unless we're in the same function.
2984 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2985 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2986 }
2987}
2988
Chris Lattner01564d92007-01-27 19:27:06 +00002989/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2990/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2991/// situation, merging decls or emitting diagnostics as appropriate.
2992///
Mike Stump11289f42009-09-09 15:08:12 +00002993/// Tentative definition rules (C99 6.9.2p2) are checked by
2994/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002995/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002996///
Richard Smith3c785782013-09-03 21:00:58 +00002997void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00002998 // If the new decl is already invalid, don't do any other checking.
2999 if (New->isInvalidDecl())
3000 return;
Mike Stump11289f42009-09-09 15:08:12 +00003001
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003002 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00003003 VarDecl *Old = 0;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003004 if (Previous.isSingleResult() &&
3005 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003006 if (New->getDescribedVarTemplate())
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003007 Old = Old->getDescribedVarTemplate() ? Old : 0;
3008 else
3009 Old = Old->getDescribedVarTemplate() ? 0 : Old;
3010 }
3011 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003012 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003013 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00003014 Diag(Previous.getRepresentativeDecl()->getLocation(),
3015 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003016 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00003017 }
Chris Lattner84966392008-03-03 03:28:21 +00003018
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00003019 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3020 return;
3021
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003022 // C++ [class.mem]p1:
3023 // A member shall not be declared twice in the member-specification [...]
3024 //
3025 // Here, we need only consider static data members.
3026 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3027 Diag(New->getLocation(), diag::err_duplicate_member)
3028 << New->getIdentifier();
3029 Diag(Old->getLocation(), diag::note_previous_declaration);
3030 New->setInvalidDecl();
3031 }
3032
Douglas Gregor32c17572012-01-01 20:30:41 +00003033 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003034 // Warn if an already-declared variable is made a weak_import in a subsequent
3035 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003036 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003037 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003038 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003039 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3040 Diag(Old->getLocation(), diag::note_previous_definition);
3041 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003042 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003043 }
Chris Lattner84966392008-03-03 03:28:21 +00003044
Richard Smith30482bc2011-02-20 03:19:35 +00003045 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003046 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3047
Richard Smith30482bc2011-02-20 03:19:35 +00003048 if (New->isInvalidDecl())
3049 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003050
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003051 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003052 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003053 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003054 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003055 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003056 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003057 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003058 }
Mike Stump11289f42009-09-09 15:08:12 +00003059 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003060 // For an identifier declared with the storage-class specifier
3061 // extern in a scope in which a prior declaration of that
3062 // identifier is visible,23) if the prior declaration specifies
3063 // internal or external linkage, the linkage of the identifier at
3064 // the later declaration is the same as the linkage specified at
3065 // the prior declaration. If no prior declaration is visible, or
3066 // if the prior declaration specifies no linkage, then the
3067 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003068 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003069 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003070 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003071 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003072 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003073 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003074 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003075 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003076 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003077
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003078 // Check if extern is followed by non-extern and vice-versa.
3079 if (New->hasExternalStorage() &&
3080 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3081 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3082 Diag(Old->getLocation(), diag::note_previous_definition);
3083 return New->setInvalidDecl();
3084 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003085 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3086 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003087 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3088 Diag(Old->getLocation(), diag::note_previous_definition);
3089 return New->setInvalidDecl();
3090 }
3091
Steve Naroffa5629372008-09-17 14:05:40 +00003092 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003093
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003094 // FIXME: The test for external storage here seems wrong? We still
3095 // need to check for mismatches.
3096 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003097 // Don't complain about out-of-line definitions of static members.
3098 !(Old->getLexicalDeclContext()->isRecord() &&
3099 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003100 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003101 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003102 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003103 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003104
Richard Smithfd3834f2013-04-13 02:43:54 +00003105 if (New->getTLSKind() != Old->getTLSKind()) {
3106 if (!Old->getTLSKind()) {
3107 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3108 Diag(Old->getLocation(), diag::note_previous_declaration);
3109 } else if (!New->getTLSKind()) {
3110 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3111 Diag(Old->getLocation(), diag::note_previous_declaration);
3112 } else {
3113 // Do not allow redeclaration to change the variable between requiring
3114 // static and dynamic initialization.
3115 // FIXME: GCC allows this, but uses the TLS keyword on the first
3116 // declaration to determine the kind. Do we need to be compatible here?
3117 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3118 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3119 Diag(Old->getLocation(), diag::note_previous_declaration);
3120 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003121 }
3122
Sebastian Redlf1842912010-02-02 18:35:11 +00003123 // C++ doesn't have tentative definitions, so go right ahead and check here.
3124 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003125 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003126 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003127 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003128 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003129 Diag(Def->getLocation(), diag::note_previous_definition);
3130 New->setInvalidDecl();
3131 return;
3132 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003133
Rafael Espindolaf4187652013-02-14 01:18:37 +00003134 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003135 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3136 Diag(Old->getLocation(), diag::note_previous_definition);
3137 New->setInvalidDecl();
3138 return;
3139 }
3140
Rafael Espindolabefe1302012-11-25 14:07:59 +00003141 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003142 if (Old->getMostRecentDecl()->isUsed(false))
3143 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003144
Douglas Gregor0760fa12009-03-10 23:43:53 +00003145 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003146 New->setPreviousDecl(Old);
John McCall401982f2010-01-20 21:53:11 +00003147
3148 // Inherit access appropriately.
3149 New->setAccess(Old->getAccess());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003150
3151 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3152 if (New->isStaticDataMember() && New->isOutOfLine())
3153 VTD->setAccess(New->getAccess());
3154 }
Chris Lattner01564d92007-01-27 19:27:06 +00003155}
3156
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003157/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3158/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003159Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003160 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003161 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003162}
3163
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003164static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003165 if (!S.Context.getLangOpts().CPlusPlus)
3166 return;
3167
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003168 if (isa<CXXRecordDecl>(Tag->getParent())) {
3169 // If this tag is the direct child of a class, number it if
3170 // it is anonymous.
3171 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3172 return;
3173 MangleNumberingContext &MCtx =
3174 S.Context.getManglingNumberContext(Tag->getParent());
3175 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3176 return;
3177 }
3178
3179 // If this tag isn't a direct child of a class, number it if it is local.
3180 Decl *ManglingContextDecl;
3181 if (MangleNumberingContext *MCtx =
3182 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3183 ManglingContextDecl)) {
3184 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3185 }
3186}
3187
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003188/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003189/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003190/// parameters to cope with template friend declarations.
3191Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3192 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003193 MultiTemplateParamsArg TemplateParams,
3194 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003195 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003196 TagDecl *Tag = 0;
3197 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3198 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003199 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003200 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003201 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003202 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003203
3204 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003205 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003206
John McCall07e91c02009-08-06 02:15:43 +00003207 // Note that the above type specs guarantee that the
3208 // type rep is a Decl, whereas in many of the others
3209 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003210 if (isa<TagDecl>(TagD))
3211 Tag = cast<TagDecl>(TagD);
3212 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3213 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003214 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003215
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003216 if (Tag) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003217 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003218 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003219 if (Tag->isInvalidDecl())
3220 return Tag;
3221 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003222
Nuno Lopese9823fa2009-12-17 11:35:26 +00003223 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3224 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3225 // or incomplete types shall not be restrict-qualified."
3226 if (TypeQuals & DeclSpec::TQ_restrict)
3227 Diag(DS.getRestrictSpecLoc(),
3228 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3229 << DS.getSourceRange();
3230 }
3231
Richard Smitha77a0a62011-08-15 21:04:07 +00003232 if (DS.isConstexprSpecified()) {
3233 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3234 // and definitions of functions and variables.
3235 if (Tag)
3236 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3237 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3238 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003239 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3240 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003241 else
3242 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3243 // Don't emit warnings after this error.
3244 return TagD;
3245 }
3246
Richard Smithb1402ae2013-03-18 22:52:47 +00003247 DiagnoseFunctionSpecifiers(DS);
3248
Douglas Gregor3dad8422009-09-26 06:47:28 +00003249 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003250 // If we're dealing with a decl but not a TagDecl, assume that
3251 // whatever routines created it handled the friendship aspect.
3252 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003253 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003254 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003255 }
John McCallaa017372011-03-22 23:00:04 +00003256
Richard Smithb1402ae2013-03-18 22:52:47 +00003257 CXXScopeSpec &SS = DS.getTypeSpecScope();
3258 bool IsExplicitSpecialization =
3259 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3260 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3261 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3262 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3263 // nested-name-specifier unless it is an explicit instantiation
3264 // or an explicit specialization.
3265 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3266 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3267 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3268 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3269 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3270 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3271 << SS.getRange();
3272 return 0;
3273 }
3274
3275 // Track whether this decl-specifier declares anything.
3276 bool DeclaresAnything = true;
3277
3278 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003279 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003280 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003281 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003282 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003283 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00003284 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003285
Richard Smithb1402ae2013-03-18 22:52:47 +00003286 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003287 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003288 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003289
Richard Smithb1402ae2013-03-18 22:52:47 +00003290 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003291 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003292 CurContext->isRecord() &&
3293 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3294 // Handle 2 kinds of anonymous struct:
3295 // struct STRUCT;
3296 // and
3297 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3298 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003299 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003300 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3301 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003302 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003303 << DS.getSourceRange();
3304 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3305 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003306 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003307
3308 // Skip all the checks below if we have a type error.
3309 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3310 (TagD && TagD->isInvalidDecl()))
3311 return TagD;
3312
3313 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003314 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3315 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3316 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003317 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3318 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003319
John McCallaa017372011-03-22 23:00:04 +00003320 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003321 // Customize diagnostic for a typedef missing a name.
3322 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003323 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003324 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003325 else
3326 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003327 }
Mike Stump11289f42009-09-09 15:08:12 +00003328
Richard Smithb1402ae2013-03-18 22:52:47 +00003329 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003330 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3331 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3332 << Tag->getTagKind()
3333 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3334
Richard Smithb1402ae2013-03-18 22:52:47 +00003335 ActOnDocumentableDecl(TagD);
3336
3337 // C 6.7/2:
3338 // A declaration [...] shall declare at least a declarator [...], a tag,
3339 // or the members of an enumeration.
3340 // C++ [dcl.dcl]p3:
3341 // [If there are no declarators], and except for the declaration of an
3342 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3343 // names into the program, or shall redeclare a name introduced by a
3344 // previous declaration.
3345 if (!DeclaresAnything) {
3346 // In C, we allow this as a (popular) extension / bug. Don't bother
3347 // producing further diagnostics for redundant qualifiers after this.
3348 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3349 return TagD;
3350 }
3351
3352 // C++ [dcl.stc]p1:
3353 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3354 // init-declarator-list of the declaration shall not be empty.
3355 // C++ [dcl.fct.spec]p1:
3356 // If a cv-qualifier appears in a decl-specifier-seq, the
3357 // init-declarator-list of the declaration shall not be empty.
3358 //
3359 // Spurious qualifiers here appear to be valid in C.
3360 unsigned DiagID = diag::warn_standalone_specifier;
3361 if (getLangOpts().CPlusPlus)
3362 DiagID = diag::ext_standalone_specifier;
3363
3364 // Note that a linkage-specification sets a storage class, but
3365 // 'extern "C" struct foo;' is actually valid and not theoretically
3366 // useless.
3367 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3368 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3369 Diag(DS.getStorageClassSpecLoc(), DiagID)
3370 << DeclSpec::getSpecifierName(SCS);
3371
Richard Smithb4a9e862013-04-12 22:46:28 +00003372 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3373 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3374 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003375 if (DS.getTypeQualifiers()) {
3376 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3377 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3378 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3379 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3380 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003381 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3382 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003383 }
3384
Eli Friedmane3217952011-12-17 00:36:09 +00003385 // Warn about ignored type attributes, for example:
3386 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003387 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003388 if (!DS.getAttributes().empty()) {
3389 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3390 if (TypeSpecType == DeclSpec::TST_class ||
3391 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003392 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003393 TypeSpecType == DeclSpec::TST_union ||
3394 TypeSpecType == DeclSpec::TST_enum) {
3395 AttributeList* attrs = DS.getAttributes().getList();
3396 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003397 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003398 << attrs->getName()
3399 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3400 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003401 TypeSpecType == DeclSpec::TST_union ? 2 :
3402 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003403 attrs = attrs->getNext();
3404 }
3405 }
3406 }
John McCallaa017372011-03-22 23:00:04 +00003407
John McCall48871652010-08-21 09:40:31 +00003408 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003409}
3410
John McCallea305ed2009-12-18 10:40:03 +00003411/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003412/// check if there's an existing declaration that can't be overloaded.
3413///
3414/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003415static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3416 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003417 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003418 DeclarationName Name,
3419 SourceLocation NameLoc,
3420 unsigned diagnostic) {
3421 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3422 Sema::ForRedeclaration);
3423 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003424
John McCallea305ed2009-12-18 10:40:03 +00003425 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003426 return false;
3427
3428 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003429 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003430 assert(PrevDecl && "Expected a non-null Decl");
3431
3432 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3433 return false;
John McCall1f82f242009-11-18 22:49:29 +00003434
John McCallea305ed2009-12-18 10:40:03 +00003435 SemaRef.Diag(NameLoc, diagnostic) << Name;
3436 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003437
3438 return true;
3439}
3440
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003441/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3442/// anonymous struct or union AnonRecord into the owning context Owner
3443/// and scope S. This routine will be invoked just after we realize
3444/// that an unnamed union or struct is actually an anonymous union or
3445/// struct, e.g.,
3446///
3447/// @code
3448/// union {
3449/// int i;
3450/// float f;
3451/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3452/// // f into the surrounding scope.x
3453/// @endcode
3454///
3455/// This routine is recursive, injecting the names of nested anonymous
3456/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003457static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003458 DeclContext *Owner,
3459 RecordDecl *AnonRecord,
3460 AccessSpecifier AS,
3461 SmallVectorImpl<NamedDecl *> &Chaining,
3462 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003463 unsigned diagKind
3464 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3465 : diag::err_anonymous_struct_member_redecl;
3466
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003467 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003468
3469 // Look every FieldDecl and IndirectFieldDecl with a name.
3470 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3471 DEnd = AnonRecord->decls_end();
3472 D != DEnd; ++D) {
3473 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3474 cast<NamedDecl>(*D)->getDeclName()) {
3475 ValueDecl *VD = cast<ValueDecl>(*D);
3476 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3477 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003478 // C++ [class.union]p2:
3479 // The names of the members of an anonymous union shall be
3480 // distinct from the names of any other entity in the
3481 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003482 Invalid = true;
3483 } else {
3484 // C++ [class.union]p2:
3485 // For the purpose of name lookup, after the anonymous union
3486 // definition, the members of the anonymous union are
3487 // considered to have been defined in the scope in which the
3488 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003489 unsigned OldChainingSize = Chaining.size();
3490 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3491 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3492 PE = IF->chain_end(); PI != PE; ++PI)
3493 Chaining.push_back(*PI);
3494 else
3495 Chaining.push_back(VD);
3496
Francois Pichet783dd6e2010-11-21 06:08:52 +00003497 assert(Chaining.size() >= 2);
3498 NamedDecl **NamedChain =
3499 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3500 for (unsigned i = 0; i < Chaining.size(); i++)
3501 NamedChain[i] = Chaining[i];
3502
3503 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003504 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3505 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003506 NamedChain, Chaining.size());
3507
3508 IndirectField->setAccess(AS);
3509 IndirectField->setImplicit();
3510 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003511
3512 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003513 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003514
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003515 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003516 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003517 }
3518 }
3519
3520 return Invalid;
3521}
3522
Douglas Gregorc4df4072010-04-19 22:54:31 +00003523/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3524/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003525/// illegal input values are mapped to SC_None.
3526static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003527StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3528 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3529 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3530 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003531 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003532 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003533 case DeclSpec::SCS_extern:
3534 if (DS.isExternInLinkageSpec())
3535 return SC_None;
3536 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003537 case DeclSpec::SCS_static: return SC_Static;
3538 case DeclSpec::SCS_auto: return SC_Auto;
3539 case DeclSpec::SCS_register: return SC_Register;
3540 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003541 // Illegal SCSs map to None: error reporting is up to the caller.
3542 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003543 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003544 }
3545 llvm_unreachable("unknown storage class specifier");
3546}
3547
Richard Smithab44d5b2013-12-10 08:25:00 +00003548static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3549 assert(Record->hasInClassInitializer());
3550
3551 for (DeclContext::decl_iterator I = Record->decls_begin(),
3552 E = Record->decls_end();
3553 I != E; ++I) {
3554 FieldDecl *FD = dyn_cast<FieldDecl>(*I);
3555 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
3556 FD = IFD->getAnonField();
3557 if (FD && FD->hasInClassInitializer())
3558 return FD->getLocation();
3559 }
3560
3561 llvm_unreachable("couldn't find in-class initializer");
3562}
3563
3564static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3565 SourceLocation DefaultInitLoc) {
3566 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3567 return;
3568
3569 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3570 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3571}
3572
3573static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3574 CXXRecordDecl *AnonUnion) {
3575 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3576 return;
3577
3578 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3579}
3580
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003581/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003582/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003583/// (C++ [class.union]) and a C11 feature; anonymous structures
3584/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003585Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3586 AccessSpecifier AS,
3587 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003588 DeclContext *Owner = Record->getDeclContext();
3589
3590 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003591 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003592 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003593 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003594 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003595 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003596 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003597
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003598 // C and C++ require different kinds of checks for anonymous
3599 // structs/unions.
3600 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003601 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003602 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003603 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003604 if (Record->isUnion()) {
3605 // C++ [class.union]p6:
3606 // Anonymous unions declared in a named namespace or in the
3607 // global namespace shall be declared static.
3608 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3609 (isa<TranslationUnitDecl>(Owner) ||
3610 (isa<NamespaceDecl>(Owner) &&
3611 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003612 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3613 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003614
3615 // Recover by adding 'static'.
3616 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3617 PrevSpec, DiagID);
3618 }
3619 // C++ [class.union]p6:
3620 // A storage class is not allowed in a declaration of an
3621 // anonymous union in a class scope.
3622 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3623 isa<RecordDecl>(Owner)) {
3624 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003625 diag::err_anonymous_union_with_storage_spec)
3626 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003627
3628 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003629 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3630 SourceLocation(),
David Blaikie0a8e8992011-10-19 22:43:29 +00003631 PrevSpec, DiagID);
3632 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003633 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003634
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003635 // Ignore const/volatile/restrict qualifiers.
3636 if (DS.getTypeQualifiers()) {
3637 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3638 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003639 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003640 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3641 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003642 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003643 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003644 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003645 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3646 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003647 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003648 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003649 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003650 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003651 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3652 Diag(DS.getAtomicSpecLoc(),
3653 diag::ext_anonymous_struct_union_qualified)
3654 << Record->isUnion() << "_Atomic"
3655 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003656
3657 DS.ClearTypeQualifiers();
3658 }
3659
Mike Stump11289f42009-09-09 15:08:12 +00003660 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003661 // The member-specification of an anonymous union shall only
3662 // define non-static data members. [Note: nested types and
3663 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003664 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3665 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003666 Mem != MemEnd; ++Mem) {
3667 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3668 // C++ [class.union]p3:
3669 // An anonymous union shall not have private or protected
3670 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003671 assert(FD->getAccess() != AS_none);
3672 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003673 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3674 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3675 Invalid = true;
3676 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003677
Alexis Hunt97ab5542011-05-16 22:41:40 +00003678 // C++ [class.union]p1
3679 // An object of a class with a non-trivial constructor, a non-trivial
3680 // copy constructor, a non-trivial destructor, or a non-trivial copy
3681 // assignment operator cannot be a member of a union, nor can an
3682 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003683 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003684 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00003685 } else if ((*Mem)->isImplicit()) {
3686 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00003687 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3688 // This is a type that showed up in an
3689 // elaborated-type-specifier inside the anonymous struct or
3690 // union, but which actually declares a type outside of the
3691 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003692 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3693 if (!MemRecord->isAnonymousStructOrUnion() &&
3694 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003695 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003696 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003697 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3698 << (int)Record->isUnion();
3699 else {
3700 // This is a nested type declaration.
3701 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3702 << (int)Record->isUnion();
3703 Invalid = true;
3704 }
Richard Smith254d2662013-01-28 00:54:05 +00003705 } else {
3706 // This is an anonymous type definition within another anonymous type.
3707 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3708 // not part of standard C++.
3709 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003710 diag::ext_anonymous_record_with_anonymous_type)
3711 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003712 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00003713 } else if (isa<AccessSpecDecl>(*Mem)) {
3714 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003715 } else {
3716 // We have something that isn't a non-static data
3717 // member. Complain about it.
3718 unsigned DK = diag::err_anonymous_record_bad_member;
3719 if (isa<TypeDecl>(*Mem))
3720 DK = diag::err_anonymous_record_with_type;
3721 else if (isa<FunctionDecl>(*Mem))
3722 DK = diag::err_anonymous_record_with_function;
3723 else if (isa<VarDecl>(*Mem))
3724 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003725
3726 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003727 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003728 DK == diag::err_anonymous_record_with_type)
3729 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003730 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003731 else {
3732 Diag((*Mem)->getLocation(), DK)
3733 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003734 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003735 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003736 }
3737 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003738
3739 // C++11 [class.union]p8 (DR1460):
3740 // At most one variant member of a union may have a
3741 // brace-or-equal-initializer.
3742 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3743 Owner->isRecord())
3744 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3745 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003746 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003747
3748 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003749 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003750 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003751 Invalid = true;
3752 }
3753
John McCallfa2d6922009-10-22 23:31:08 +00003754 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003755 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003756 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003757 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003758
Mike Stump11289f42009-09-09 15:08:12 +00003759 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003760 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003761 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003762 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003763 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003764 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003765 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003766 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003767 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003768 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003769 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003770 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003771 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003772 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003773 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003774 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003775 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003776 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003777 // mutable can only appear on non-static class members, so it's always
3778 // an error here
3779 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3780 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003781 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003782 }
3783
Abramo Bagnaradff19302011-03-08 08:55:46 +00003784 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003785 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003786 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003787 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003788 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003789
3790 // Default-initialize the implicit variable. This initialization will be
3791 // trivial in almost all cases, except if a union member has an in-class
3792 // initializer:
3793 // union { int n = 0; };
3794 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003795 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003796 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003797
Richard Smithab44d5b2013-12-10 08:25:00 +00003798 // Mark this as an anonymous struct/union type.
3799 Record->setAnonymousStructOrUnion(true);
3800
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003801 // Add the anonymous struct/union object to the current
3802 // context. We'll be referencing this object when we refer to one of
3803 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003804 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003805
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003806 // Inject the members of the anonymous struct/union into the owning
3807 // context and into the identifier resolver chain for name lookup
3808 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003809 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003810 Chain.push_back(Anon);
3811
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003812 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3813 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003814 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003815
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003816 if (Invalid)
3817 Anon->setInvalidDecl();
3818
John McCall48871652010-08-21 09:40:31 +00003819 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003820}
3821
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003822/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3823/// Microsoft C anonymous structure.
3824/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3825/// Example:
3826///
3827/// struct A { int a; };
3828/// struct B { struct A; int b; };
3829///
3830/// void foo() {
3831/// B var;
3832/// var.a = 3;
3833/// }
3834///
3835Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3836 RecordDecl *Record) {
3837
3838 // If there is no Record, get the record via the typedef.
3839 if (!Record)
3840 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3841
3842 // Mock up a declarator.
3843 Declarator Dc(DS, Declarator::TypeNameContext);
3844 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3845 assert(TInfo && "couldn't build declarator info for anonymous struct");
3846
3847 // Create a declaration for this anonymous struct.
3848 NamedDecl* Anon = FieldDecl::Create(Context,
3849 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003850 DS.getLocStart(),
3851 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003852 /*IdentifierInfo=*/0,
3853 Context.getTypeDeclType(Record),
3854 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003855 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003856 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003857 Anon->setImplicit();
3858
3859 // Add the anonymous struct object to the current context.
3860 CurContext->addDecl(Anon);
3861
3862 // Inject the members of the anonymous struct into the current
3863 // context and into the identifier resolver chain for name lookup
3864 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003865 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003866 Chain.push_back(Anon);
3867
Nico Weberf8bb3de2012-02-01 00:41:00 +00003868 RecordDecl *RecordDef = Record->getDefinition();
3869 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3870 RecordDef, AS_none,
3871 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003872 Anon->setInvalidDecl();
3873
3874 return Anon;
3875}
Steve Naroff2fea1392007-09-02 02:04:30 +00003876
Douglas Gregor92751d42008-11-17 22:58:34 +00003877/// GetNameForDeclarator - Determine the full declaration name for the
3878/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003879DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003880 return GetNameFromUnqualifiedId(D.getName());
3881}
3882
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003883/// \brief Retrieves the declaration name from a parsed unqualified-id.
3884DeclarationNameInfo
3885Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3886 DeclarationNameInfo NameInfo;
3887 NameInfo.setLoc(Name.StartLocation);
3888
Douglas Gregor7861a802009-11-03 01:35:08 +00003889 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003890
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003891 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003892 case UnqualifiedId::IK_Identifier:
3893 NameInfo.setName(Name.Identifier);
3894 NameInfo.setLoc(Name.StartLocation);
3895 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003896
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003897 case UnqualifiedId::IK_OperatorFunctionId:
3898 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3899 Name.OperatorFunctionId.Operator));
3900 NameInfo.setLoc(Name.StartLocation);
3901 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3902 = Name.OperatorFunctionId.SymbolLocations[0];
3903 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3904 = Name.EndLocation.getRawEncoding();
3905 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003906
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003907 case UnqualifiedId::IK_LiteralOperatorId:
3908 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3909 Name.Identifier));
3910 NameInfo.setLoc(Name.StartLocation);
3911 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3912 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003913
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003914 case UnqualifiedId::IK_ConversionFunctionId: {
3915 TypeSourceInfo *TInfo;
3916 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3917 if (Ty.isNull())
3918 return DeclarationNameInfo();
3919 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3920 Context.getCanonicalType(Ty)));
3921 NameInfo.setLoc(Name.StartLocation);
3922 NameInfo.setNamedTypeInfo(TInfo);
3923 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003924 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003925
3926 case UnqualifiedId::IK_ConstructorName: {
3927 TypeSourceInfo *TInfo;
3928 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3929 if (Ty.isNull())
3930 return DeclarationNameInfo();
3931 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3932 Context.getCanonicalType(Ty)));
3933 NameInfo.setLoc(Name.StartLocation);
3934 NameInfo.setNamedTypeInfo(TInfo);
3935 return NameInfo;
3936 }
3937
3938 case UnqualifiedId::IK_ConstructorTemplateId: {
3939 // In well-formed code, we can only have a constructor
3940 // template-id that refers to the current context, so go there
3941 // to find the actual type being constructed.
3942 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3943 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3944 return DeclarationNameInfo();
3945
3946 // Determine the type of the class being constructed.
3947 QualType CurClassType = Context.getTypeDeclType(CurClass);
3948
3949 // FIXME: Check two things: that the template-id names the same type as
3950 // CurClassType, and that the template-id does not occur when the name
3951 // was qualified.
3952
3953 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3954 Context.getCanonicalType(CurClassType)));
3955 NameInfo.setLoc(Name.StartLocation);
3956 // FIXME: should we retrieve TypeSourceInfo?
3957 NameInfo.setNamedTypeInfo(0);
3958 return NameInfo;
3959 }
3960
3961 case UnqualifiedId::IK_DestructorName: {
3962 TypeSourceInfo *TInfo;
3963 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3964 if (Ty.isNull())
3965 return DeclarationNameInfo();
3966 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3967 Context.getCanonicalType(Ty)));
3968 NameInfo.setLoc(Name.StartLocation);
3969 NameInfo.setNamedTypeInfo(TInfo);
3970 return NameInfo;
3971 }
3972
3973 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003974 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003975 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3976 return Context.getNameForTemplate(TName, TNameLoc);
3977 }
3978
3979 } // switch (Name.getKind())
3980
David Blaikie83d382b2011-09-23 05:06:16 +00003981 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003982}
3983
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003984static QualType getCoreType(QualType Ty) {
3985 do {
3986 if (Ty->isPointerType() || Ty->isReferenceType())
3987 Ty = Ty->getPointeeType();
3988 else if (Ty->isArrayType())
3989 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3990 else
3991 return Ty.withoutLocalFastQualifiers();
3992 } while (true);
3993}
3994
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003995/// hasSimilarParameters - Determine whether the C++ functions Declaration
3996/// and Definition have "nearly" matching parameters. This heuristic is
3997/// used to improve diagnostics in the case where an out-of-line function
3998/// definition doesn't match any declaration within the class or namespace.
3999/// Also sets Params to the list of indices to the parameters that differ
4000/// between the declaration and the definition. If hasSimilarParameters
4001/// returns true and Params is empty, then all of the parameters match.
4002static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00004003 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004004 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004005 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004006 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00004007 if (Declaration->param_size() != Definition->param_size())
4008 return false;
4009 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4010 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4011 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4012
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004013 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00004014 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004015 continue;
4016
4017 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4018 QualType DefParamBaseTy = getCoreType(DefParamTy);
4019 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4020 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4021
4022 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4023 (DeclTyName && DeclTyName == DefTyName))
4024 Params.push_back(Idx);
4025 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004026 return false;
4027 }
4028
4029 return true;
4030}
4031
John McCall99b2fe52010-04-29 23:50:39 +00004032/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4033/// declarator needs to be rebuilt in the current instantiation.
4034/// Any bits of declarator which appear before the name are valid for
4035/// consideration here. That's specifically the type in the decl spec
4036/// and the base type in any member-pointer chunks.
4037static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4038 DeclarationName Name) {
4039 // The types we specifically need to rebuild are:
4040 // - typenames, typeofs, and decltypes
4041 // - types which will become injected class names
4042 // Of course, we also need to rebuild any type referencing such a
4043 // type. It's safest to just say "dependent", but we call out a
4044 // few cases here.
4045
4046 DeclSpec &DS = D.getMutableDeclSpec();
4047 switch (DS.getTypeSpecType()) {
4048 case DeclSpec::TST_typename:
4049 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004050 case DeclSpec::TST_underlyingType:
4051 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004052 // Grab the type from the parser.
4053 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004054 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004055 if (T.isNull() || !T->isDependentType()) break;
4056
4057 // Make sure there's a type source info. This isn't really much
4058 // of a waste; most dependent types should have type source info
4059 // attached already.
4060 if (!TSI)
4061 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4062
4063 // Rebuild the type in the current instantiation.
4064 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4065 if (!TSI) return true;
4066
4067 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004068 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4069 DS.UpdateTypeRep(LocType);
4070 break;
4071 }
4072
Richard Smith1620ebd2012-10-01 20:35:07 +00004073 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004074 case DeclSpec::TST_typeofExpr: {
4075 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004076 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004077 if (Result.isInvalid()) return true;
4078 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004079 break;
4080 }
4081
4082 default:
4083 // Nothing to do for these decl specs.
4084 break;
4085 }
4086
4087 // It doesn't matter what order we do this in.
4088 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4089 DeclaratorChunk &Chunk = D.getTypeObject(I);
4090
4091 // The only type information in the declarator which can come
4092 // before the declaration name is the base type of a member
4093 // pointer.
4094 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4095 continue;
4096
4097 // Rebuild the scope specifier in-place.
4098 CXXScopeSpec &SS = Chunk.Mem.Scope();
4099 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4100 return true;
4101 }
4102
4103 return false;
4104}
4105
Anders Carlsson1052fd72011-07-04 16:28:17 +00004106Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004107 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004108 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004109
4110 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004111 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004112 Dcl->setTopLevelDeclInObjCContainer();
4113
4114 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004115}
4116
Richard Smithdda56e42011-04-15 14:24:37 +00004117/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4118/// If T is the name of a class, then each of the following shall have a
4119/// name different from T:
4120/// - every static data member of class T;
4121/// - every member function of class T
4122/// - every member of class T that is itself a type;
4123/// \returns true if the declaration name violates these rules.
4124bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4125 DeclarationNameInfo NameInfo) {
4126 DeclarationName Name = NameInfo.getName();
4127
4128 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4129 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4130 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4131 return true;
4132 }
4133
4134 return false;
4135}
Douglas Gregor31feb332012-03-17 23:06:31 +00004136
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004137/// \brief Diagnose a declaration whose declarator-id has the given
4138/// nested-name-specifier.
4139///
4140/// \param SS The nested-name-specifier of the declarator-id.
4141///
4142/// \param DC The declaration context to which the nested-name-specifier
4143/// resolves.
4144///
4145/// \param Name The name of the entity being declared.
4146///
4147/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004148///
4149/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004150bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004151 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004152 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004153 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004154 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004155 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004156
4157 // If the user provided a superfluous scope specifier that refers back to the
4158 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004159 //
4160 // class X {
4161 // void X::f();
4162 // };
Richard Smitha2302242013-12-05 07:51:02 +00004163 //
4164 // Note, it was once ill-formed to give redundant qualification in all
4165 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004166 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004167 if (Cur->isRecord()) {
4168 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4169 : diag::err_member_extra_qualification)
4170 << Name << FixItHint::CreateRemoval(SS.getRange());
4171 SS.clear();
4172 } else {
4173 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4174 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004175 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004176 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004177
4178 // Check whether the qualifying scope encloses the scope of the original
4179 // declaration.
4180 if (!Cur->Encloses(DC)) {
4181 if (Cur->isRecord())
4182 Diag(Loc, diag::err_member_qualification)
4183 << Name << SS.getRange();
4184 else if (isa<TranslationUnitDecl>(DC))
4185 Diag(Loc, diag::err_invalid_declarator_global_scope)
4186 << Name << SS.getRange();
4187 else if (isa<FunctionDecl>(Cur))
4188 Diag(Loc, diag::err_invalid_declarator_in_function)
4189 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004190 else if (isa<BlockDecl>(Cur))
4191 Diag(Loc, diag::err_invalid_declarator_in_block)
4192 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004193 else
4194 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004195 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004196
Douglas Gregor31feb332012-03-17 23:06:31 +00004197 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004198 }
4199
4200 if (Cur->isRecord()) {
4201 // Cannot qualify members within a class.
4202 Diag(Loc, diag::err_member_qualification)
4203 << Name << SS.getRange();
4204 SS.clear();
4205
4206 // C++ constructors and destructors with incorrect scopes can break
4207 // our AST invariants by having the wrong underlying types. If
4208 // that's the case, then drop this declaration entirely.
4209 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4210 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4211 !Context.hasSameType(Name.getCXXNameType(),
4212 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4213 return true;
4214
4215 return false;
4216 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004217
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004218 // C++11 [dcl.meaning]p1:
4219 // [...] "The nested-name-specifier of the qualified declarator-id shall
4220 // not begin with a decltype-specifer"
4221 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4222 while (SpecLoc.getPrefix())
4223 SpecLoc = SpecLoc.getPrefix();
4224 if (dyn_cast_or_null<DecltypeType>(
4225 SpecLoc.getNestedNameSpecifier()->getAsType()))
4226 Diag(Loc, diag::err_decltype_in_declarator)
4227 << SpecLoc.getTypeLoc().getSourceRange();
4228
Douglas Gregor31feb332012-03-17 23:06:31 +00004229 return false;
4230}
4231
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004232NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4233 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004234 // TODO: consider using NameInfo for diagnostic.
4235 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4236 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004237
Chris Lattner02c04392007-07-25 00:24:17 +00004238 // All of these full declarators require an identifier. If it doesn't have
4239 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004240 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004241 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004242 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004243 diag::err_declarator_need_ident)
4244 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004245 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004246 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4247 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004248
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004249 // The scope passed in may not be a decl scope. Zip up the scope tree until
4250 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004251 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004252 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004253 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004254
John McCall99b2fe52010-04-29 23:50:39 +00004255 DeclContext *DC = CurContext;
4256 if (D.getCXXScopeSpec().isInvalid())
4257 D.setInvalidType();
4258 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004259 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4260 UPPC_DeclarationQualifier))
4261 return 0;
4262
John McCall99b2fe52010-04-29 23:50:39 +00004263 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4264 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004265 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004266 // If we could not compute the declaration context, it's because the
4267 // declaration context is dependent but does not refer to a class,
4268 // class template, or class template partial specialization. Complain
4269 // and return early, to avoid the coming semantic disaster.
4270 Diag(D.getIdentifierLoc(),
4271 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004272 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004273 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004274 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004275 }
John McCall99b2fe52010-04-29 23:50:39 +00004276 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004277
John McCall99b2fe52010-04-29 23:50:39 +00004278 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004279 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004280 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004281
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004282 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4283 Diag(D.getIdentifierLoc(),
4284 diag::err_member_def_undefined_record)
4285 << Name << DC << D.getCXXScopeSpec().getRange();
4286 D.setInvalidType();
4287 } else if (!D.getDeclSpec().isFriendSpecified()) {
4288 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4289 Name, D.getIdentifierLoc())) {
4290 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004291 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004292
4293 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004294 }
John McCall99b2fe52010-04-29 23:50:39 +00004295 }
4296
4297 // Check whether we need to rebuild the type of the given
4298 // declaration in the current instantiation.
4299 if (EnteringContext && IsDependentContext &&
4300 TemplateParamLists.size() != 0) {
4301 ContextRAII SavedContext(*this, DC);
4302 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4303 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004304 }
4305 }
Richard Smithdda56e42011-04-15 14:24:37 +00004306
4307 if (DiagnoseClassNameShadow(DC, NameInfo))
4308 // If this is a typedef, we'll end up spewing multiple diagnostics.
4309 // Just return early; it's safer.
4310 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4311 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004312
John McCall8cb7bdf2010-06-04 23:28:52 +00004313 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4314 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004315
Douglas Gregor506bd562010-12-13 22:49:22 +00004316 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4317 UPPC_DeclarationType))
4318 D.setInvalidType();
4319
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004320 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004321 ForRedeclaration);
4322
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004323 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004324 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004325 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004326 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004327
4328 // If the declaration we're planning to build will be a function
4329 // or object with linkage, then look for another declaration with
4330 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004331 //
4332 // If the declaration we're planning to build will be declared with
4333 // external linkage in the translation unit, create any builtin with
4334 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004335 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4336 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004337 else if (CurContext->isFunctionOrMethod() &&
4338 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4339 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004340 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004341 CreateBuiltins =
4342 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4343 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4344 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4345 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004346
4347 if (IsLinkageLookup)
4348 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004349
Richard Smith1c34fb72013-08-13 18:18:50 +00004350 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004351 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004352 LookupQualifiedName(Previous, DC);
4353
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004354 // C++ [dcl.meaning]p1:
4355 // When the declarator-id is qualified, the declaration shall refer to a
4356 // previously declared member of the class or namespace to which the
4357 // qualifier refers (or, in the case of a namespace, of an element of the
4358 // inline namespace set of that namespace (7.3.1)) or to a specialization
4359 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004360 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004361 // Note that we already checked the context above, and that we do not have
4362 // enough information to make sure that Previous contains the declaration
4363 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004364 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004365 // class X {
4366 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004367 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004368 // };
4369 //
Douglas Gregorad590502008-12-15 23:53:10 +00004370 // void X::f(int) { } // ill-formed
4371 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004372 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004373 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004374 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004375
4376 // C++ [dcl.meaning]p1:
4377 // [...] the member shall not merely have been introduced by a
4378 // using-declaration in the scope of the class or namespace nominated by
4379 // the nested-name-specifier of the declarator-id.
4380 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004381 }
4382
John McCall1f82f242009-11-18 22:49:29 +00004383 if (Previous.isSingleResult() &&
4384 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004385 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004386 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004387 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4388 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004389
Douglas Gregor5101c242008-12-05 18:15:24 +00004390 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004391 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004392 }
4393
Douglas Gregor83a586e2008-04-13 21:07:44 +00004394 // In C++, the previous declaration we find might be a tag type
4395 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004396 // tag type. Note that this does does not apply if we're declaring a
4397 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004398 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004399 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004400 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004401
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004402 // Check that there are no default arguments other than in the parameters
4403 // of a function declaration (C++ only).
4404 if (getLangOpts().CPlusPlus)
4405 CheckExtraCXXDefaultArguments(D);
4406
Nico Webercb4c7f42012-12-23 00:40:46 +00004407 NamedDecl *New;
4408
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004409 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004410 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004411 if (TemplateParamLists.size()) {
4412 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004413 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004414 }
Mike Stump11289f42009-09-09 15:08:12 +00004415
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004416 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004417 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004418 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004419 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004420 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004421 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004422 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4423 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004424 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004425
4426 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004427 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004428
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004429 // If this has an identifier and is not an invalid redeclaration or
4430 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004431 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004432 !(D.isRedeclaration() && New->isInvalidDecl())) {
4433 // Only make a locally-scoped extern declaration visible if it is the first
4434 // declaration of this entity. Qualified lookup for such an entity should
4435 // only find this declaration if there is no visible declaration of it.
4436 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4437 PushOnScopeChains(New, S, AddToContext);
4438 if (!AddToContext)
4439 CurContext->addHiddenDecl(New);
4440 }
Mike Stump11289f42009-09-09 15:08:12 +00004441
John McCall48871652010-08-21 09:40:31 +00004442 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004443}
4444
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004445/// Helper method to turn variable array types into constant array
4446/// types in certain situations which would otherwise be errors (for
4447/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004448static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4449 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004450 bool &SizeIsNegative,
4451 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004452 // This method tries to turn a variable array into a constant
4453 // array even when the size isn't an ICE. This is necessary
4454 // for compatibility with code that depends on gcc's buggy
4455 // constant expression folding, like struct {char x[(int)(char*)2];}
4456 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004457 Oversized = 0;
4458
4459 if (T->isDependentType())
4460 return QualType();
4461
John McCall8ccfcb52009-09-24 19:53:00 +00004462 QualifierCollector Qs;
4463 const Type *Ty = Qs.strip(T);
4464
4465 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004466 QualType Pointee = PTy->getPointeeType();
4467 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004468 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4469 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004470 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004471 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004472 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004473 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004474 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4475 QualType Inner = PTy->getInnerType();
4476 QualType FixedType =
4477 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4478 Oversized);
4479 if (FixedType.isNull()) return FixedType;
4480 FixedType = Context.getParenType(FixedType);
4481 return Qs.apply(Context, FixedType);
4482 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004483
4484 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004485 if (!VLATy)
4486 return QualType();
4487 // FIXME: We should probably handle this case
4488 if (VLATy->getElementType()->isVariablyModifiedType())
4489 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004490
Richard Smith42d3af92011-12-07 00:43:50 +00004491 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004492 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004493 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004494 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004495
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004496 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004497 if (Res.isSigned() && Res.isNegative()) {
4498 SizeIsNegative = true;
4499 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004500 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004501
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004502 // Check whether the array is too large to be addressed.
4503 unsigned ActiveSizeBits
4504 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4505 Res);
4506 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4507 Oversized = Res;
4508 return QualType();
4509 }
4510
4511 return Context.getConstantArrayType(VLATy->getElementType(),
4512 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004513}
4514
Abramo Bagnara341ab732012-11-08 14:44:42 +00004515static void
4516FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004517 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4518 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4519 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4520 DstPTL.getPointeeLoc());
4521 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004522 return;
4523 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004524 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4525 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4526 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4527 DstPTL.getInnerLoc());
4528 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4529 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004530 return;
4531 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004532 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4533 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4534 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4535 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004536 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004537 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4538 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4539 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004540}
4541
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004542/// Helper method to turn variable array types into constant array
4543/// types in certain situations which would otherwise be errors (for
4544/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004545static TypeSourceInfo*
4546TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4547 ASTContext &Context,
4548 bool &SizeIsNegative,
4549 llvm::APSInt &Oversized) {
4550 QualType FixedTy
4551 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4552 SizeIsNegative, Oversized);
4553 if (FixedTy.isNull())
4554 return 0;
4555 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4556 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4557 FixedTInfo->getTypeLoc());
4558 return FixedTInfo;
4559}
4560
Richard Smith78165b52013-01-10 23:43:47 +00004561/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004562/// that it can be found later for redeclarations. We include any extern "C"
4563/// declaration that is not visible in the translation unit here, not just
4564/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004565void
Richard Smith39b79682013-06-18 20:15:12 +00004566Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004567 if (!getLangOpts().CPlusPlus &&
4568 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4569 // Don't need to track declarations in the TU in C.
4570 return;
4571
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004572 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004573 // FIXME: There can be multiple such declarations if they are functions marked
4574 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004575 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004576}
4577
Richard Smith39b79682013-06-18 20:15:12 +00004578NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004579 if (ExternalSource) {
4580 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004581 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004582 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004583 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004584 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4585 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004586 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4587 if (Pos == LocallyScopedExternCDecls.end())
4588 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004589 }
4590 }
Richard Smith39b79682013-06-18 20:15:12 +00004591
4592 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004593 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004594}
4595
Eli Friedman574c7452009-04-07 19:37:57 +00004596/// \brief Diagnose function specifiers on a declaration of an identifier that
4597/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004598void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004599 // FIXME: We should probably indicate the identifier in question to avoid
4600 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004601 if (DS.isInlineSpecified())
4602 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004603 diag::err_inline_non_function);
4604
Richard Smithb1402ae2013-03-18 22:52:47 +00004605 if (DS.isVirtualSpecified())
4606 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004607 diag::err_virtual_non_function);
4608
Richard Smithb1402ae2013-03-18 22:52:47 +00004609 if (DS.isExplicitSpecified())
4610 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004611 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004612
Richard Smithb1402ae2013-03-18 22:52:47 +00004613 if (DS.isNoreturnSpecified())
4614 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004615 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004616}
4617
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004618NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004619Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004620 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004621 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4622 if (D.getCXXScopeSpec().isSet()) {
4623 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4624 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004625 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004626 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004627 DC = CurContext;
4628 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004629 }
4630
Richard Smithb1402ae2013-03-18 22:52:47 +00004631 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004632
Richard Smitha77a0a62011-08-15 21:04:07 +00004633 if (D.getDeclSpec().isConstexprSpecified())
4634 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4635 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004636
Douglas Gregord8f446f2010-07-13 06:37:01 +00004637 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4638 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4639 << D.getName().getSourceRange();
4640 return 0;
4641 }
4642
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004643 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004644 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004645
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004646 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004647 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004648
Richard Smith3f1b5d02011-05-05 21:57:07 +00004649 CheckTypedefForVariablyModifiedType(S, NewTD);
4650
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004651 bool Redeclaration = D.isRedeclaration();
4652 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4653 D.setRedeclaration(Redeclaration);
4654 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004655}
4656
Richard Smith3f1b5d02011-05-05 21:57:07 +00004657void
4658Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004659 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4660 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004661 // Note that variably modified types must be fixed before merging the decl so
4662 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004663 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4664 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004665 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004666 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004667
Chris Lattner9fecd742009-04-19 05:21:20 +00004668 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004669 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004670 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004671 TypeSourceInfo *FixedTInfo =
4672 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4673 SizeIsNegative,
4674 Oversized);
4675 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004676 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004677 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004678 } else {
4679 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004680 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004681 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004682 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004683 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004684 Diag(NewTD->getLocation(), diag::err_array_too_large)
4685 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004686 else
Richard Smithdda56e42011-04-15 14:24:37 +00004687 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004688 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004689 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004690 }
4691 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004692}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004693
Richard Smith3f1b5d02011-05-05 21:57:07 +00004694
4695/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4696/// declares a typedef-name, either using the 'typedef' type specifier or via
4697/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4698NamedDecl*
4699Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4700 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004701 // Merge the decl with the existing one if appropriate. If the decl is
4702 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004703 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4704 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004705 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004706 if (!Previous.empty()) {
4707 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004708 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004709 }
4710
Douglas Gregor27821ce2009-07-07 16:35:42 +00004711 // If this is the C FILE type, notify the AST context.
4712 if (IdentifierInfo *II = NewTD->getIdentifier())
4713 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004714 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004715 if (II->isStr("FILE"))
4716 Context.setFILEDecl(NewTD);
4717 else if (II->isStr("jmp_buf"))
4718 Context.setjmp_bufDecl(NewTD);
4719 else if (II->isStr("sigjmp_buf"))
4720 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004721 else if (II->isStr("ucontext_t"))
4722 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004723 }
4724
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004725 return NewTD;
4726}
4727
Douglas Gregor5d68a202009-02-24 19:23:27 +00004728/// \brief Determines whether the given declaration is an out-of-scope
4729/// previous declaration.
4730///
4731/// This routine should be invoked when name lookup has found a
4732/// previous declaration (PrevDecl) that is not in the scope where a
4733/// new declaration by the same name is being introduced. If the new
4734/// declaration occurs in a local scope, previous declarations with
4735/// linkage may still be considered previous declarations (C99
4736/// 6.2.2p4-5, C++ [basic.link]p6).
4737///
4738/// \param PrevDecl the previous declaration found by name
4739/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004740///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004741/// \param DC the context in which the new declaration is being
4742/// declared.
4743///
4744/// \returns true if PrevDecl is an out-of-scope previous declaration
4745/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004746static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004747isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4748 ASTContext &Context) {
4749 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004750 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004751
Douglas Gregoreddf4332009-02-24 20:03:32 +00004752 if (!PrevDecl->hasLinkage())
4753 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004754
David Blaikiebbafb8a2012-03-11 07:00:24 +00004755 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004756 // C++ [basic.link]p6:
4757 // If there is a visible declaration of an entity with linkage
4758 // having the same name and type, ignoring entities declared
4759 // outside the innermost enclosing namespace scope, the block
4760 // scope declaration declares that same entity and receives the
4761 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004762 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004763 if (!OuterContext->isFunctionOrMethod())
4764 // This rule only applies to block-scope declarations.
4765 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004766
4767 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4768 if (PrevOuterContext->isRecord())
4769 // We found a member function: ignore it.
4770 return false;
4771
4772 // Find the innermost enclosing namespace for the new and
4773 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004774 OuterContext = OuterContext->getEnclosingNamespaceContext();
4775 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004776
Douglas Gregorfcee9462010-08-27 22:55:10 +00004777 // The previous declaration is in a different namespace, so it
4778 // isn't the same function.
4779 if (!OuterContext->Equals(PrevOuterContext))
4780 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004781 }
4782
Douglas Gregor5d68a202009-02-24 19:23:27 +00004783 return true;
4784}
4785
John McCall3e11ebe2010-03-15 10:12:16 +00004786static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4787 CXXScopeSpec &SS = D.getCXXScopeSpec();
4788 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004789 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004790}
4791
John McCall31168b02011-06-15 23:02:42 +00004792bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4793 QualType type = decl->getType();
4794 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4795 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4796 // Various kinds of declaration aren't allowed to be __autoreleasing.
4797 unsigned kind = -1U;
4798 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4799 if (var->hasAttr<BlocksAttr>())
4800 kind = 0; // __block
4801 else if (!var->hasLocalStorage())
4802 kind = 1; // global
4803 } else if (isa<ObjCIvarDecl>(decl)) {
4804 kind = 3; // ivar
4805 } else if (isa<FieldDecl>(decl)) {
4806 kind = 2; // field
4807 }
4808
4809 if (kind != -1U) {
4810 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4811 << kind;
4812 }
4813 } else if (lifetime == Qualifiers::OCL_None) {
4814 // Try to infer lifetime.
4815 if (!type->isObjCLifetimeType())
4816 return false;
4817
4818 lifetime = type->getObjCARCImplicitLifetime();
4819 type = Context.getLifetimeQualifiedType(type, lifetime);
4820 decl->setType(type);
4821 }
4822
4823 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4824 // Thread-local variables cannot have lifetime.
4825 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004826 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004827 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004828 << var->getType();
4829 return true;
4830 }
4831 }
4832
4833 return false;
4834}
4835
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004836static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4837 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004838 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004839 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004840 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4841 ND.dropAttr<WeakAttr>();
4842 }
4843 }
4844 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004845 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004846 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4847 ND.dropAttr<WeakRefAttr>();
4848 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004849 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004850
4851 // 'selectany' only applies to externally visible varable declarations.
4852 // It does not apply to functions.
4853 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4854 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4855 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4856 ND.dropAttr<SelectAnyAttr>();
4857 }
4858 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004859}
4860
John McCallc87d9722013-04-02 02:48:58 +00004861/// Given that we are within the definition of the given function,
4862/// will that definition behave like C99's 'inline', where the
4863/// definition is discarded except for optimization purposes?
4864static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4865 // Try to avoid calling GetGVALinkageForFunction.
4866
4867 // All cases of this require the 'inline' keyword.
4868 if (!FD->isInlined()) return false;
4869
4870 // This is only possible in C++ with the gnu_inline attribute.
4871 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4872 return false;
4873
4874 // Okay, go ahead and call the relatively-more-expensive function.
4875
4876#ifndef NDEBUG
4877 // AST quite reasonably asserts that it's working on a function
4878 // definition. We don't really have a way to tell it that we're
4879 // currently defining the function, so just lie to it in +Asserts
4880 // builds. This is an awful hack.
4881 FD->setLazyBody(1);
4882#endif
4883
4884 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4885
4886#ifndef NDEBUG
4887 FD->setLazyBody(0);
4888#endif
4889
4890 return isC99Inline;
4891}
4892
Richard Smithac974a32013-06-30 09:48:50 +00004893/// Determine whether a variable is extern "C" prior to attaching
4894/// an initializer. We can't just call isExternC() here, because that
4895/// will also compute and cache whether the declaration is externally
4896/// visible, which might change when we attach the initializer.
4897///
4898/// This can only be used if the declaration is known to not be a
4899/// redeclaration of an internal linkage declaration.
4900///
4901/// For instance:
4902///
4903/// auto x = []{};
4904///
4905/// Attaching the initializer here makes this declaration not externally
4906/// visible, because its type has internal linkage.
4907///
4908/// FIXME: This is a hack.
4909template<typename T>
4910static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4911 if (S.getLangOpts().CPlusPlus) {
4912 // In C++, the overloadable attribute negates the effects of extern "C".
4913 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4914 return false;
4915 }
4916 return D->isExternC();
4917}
4918
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004919static bool shouldConsiderLinkage(const VarDecl *VD) {
4920 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4921 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004922 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004923 if (DC->isFileContext())
4924 return true;
4925 if (DC->isRecord())
4926 return false;
4927 llvm_unreachable("Unexpected context");
4928}
4929
4930static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4931 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4932 if (DC->isFileContext() || DC->isFunctionOrMethod())
4933 return true;
4934 if (DC->isRecord())
4935 return false;
4936 llvm_unreachable("Unexpected context");
4937}
4938
Richard Smith541b38b2013-09-20 01:15:31 +00004939/// Adjust the \c DeclContext for a function or variable that might be a
4940/// function-local external declaration.
4941bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4942 if (!DC->isFunctionOrMethod())
4943 return false;
4944
4945 // If this is a local extern function or variable declared within a function
4946 // template, don't add it into the enclosing namespace scope until it is
4947 // instantiated; it might have a dependent type right now.
4948 if (DC->isDependentContext())
4949 return true;
4950
4951 // C++11 [basic.link]p7:
4952 // When a block scope declaration of an entity with linkage is not found to
4953 // refer to some other declaration, then that entity is a member of the
4954 // innermost enclosing namespace.
4955 //
4956 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4957 // semantically-enclosing namespace, not a lexically-enclosing one.
4958 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4959 DC = DC->getParent();
4960 return true;
4961}
4962
Larisse Voufo39a1e502013-08-06 01:03:05 +00004963NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00004964Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004965 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004966 MultiTemplateParamsArg TemplateParamLists,
4967 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004968 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004969 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004970
Douglas Gregorc4df4072010-04-19 22:54:31 +00004971 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00004972 VarDecl::StorageClass SC =
4973 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00004974
Richard Smith541b38b2013-09-20 01:15:31 +00004975 DeclContext *OriginalDC = DC;
4976 bool IsLocalExternDecl = SC == SC_Extern &&
4977 adjustContextForLocalExternDecl(DC);
4978
Richard Smith5990db62013-04-15 08:33:22 +00004979 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004980 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4981 // half array type (unless the cl_khr_fp16 extension is enabled).
4982 if (Context.getBaseElementType(R)->isHalfType()) {
4983 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4984 D.setInvalidType();
4985 }
4986 }
4987
Douglas Gregorc4df4072010-04-19 22:54:31 +00004988 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004989 // mutable can only appear on non-static class members, so it's always
4990 // an error here
4991 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004992 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004993 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004994 }
John McCallc87d9722013-04-02 02:48:58 +00004995
Richard Smithf2c9afc2013-06-17 01:34:01 +00004996 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4997 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4998 D.getDeclSpec().getStorageClassSpecLoc())) {
4999 // In C++11, the 'register' storage class specifier is deprecated.
5000 // Suppress the warning in system macros, it's used in macros in some
5001 // popular C system headers, such as in glibc's htonl() macro.
5002 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5003 diag::warn_deprecated_register)
5004 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5005 }
5006
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005007 IdentifierInfo *II = Name.getAsIdentifierInfo();
5008 if (!II) {
5009 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00005010 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005011 return 0;
5012 }
5013
Richard Smithb1402ae2013-03-18 22:52:47 +00005014 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00005015
Douglas Gregor212cab32009-03-11 20:22:50 +00005016 if (!DC->isRecord() && S->getFnParent() == 0) {
5017 // C99 6.9p2: The storage-class specifiers auto and register shall not
5018 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00005019 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005020 // If this is a register variable with an asm label specified, then this
5021 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00005022 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005023 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5024 else
5025 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005026 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005027 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005028 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005029
David Blaikiebbafb8a2012-03-11 07:00:24 +00005030 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005031 // Set up the special work-group-local storage class for variables in the
5032 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005033 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005034 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005035 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005036
Guy Benyei61054192013-02-07 10:55:47 +00005037 // OpenCL v1.2 s6.9.b p4:
5038 // The sampler type cannot be used with the __local and __global address
5039 // space qualifiers.
5040 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5041 R.getAddressSpace() == LangAS::opencl_global)) {
5042 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5043 }
5044
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005045 // OpenCL 1.2 spec, p6.9 r:
5046 // The event type cannot be used to declare a program scope variable.
5047 // The event type cannot be used with the __local, __constant and __global
5048 // address space qualifiers.
5049 if (R->isEventT()) {
5050 if (S->getParent() == 0) {
5051 Diag(D.getLocStart(), diag::err_event_t_global_var);
5052 D.setInvalidType();
5053 }
5054
5055 if (R.getAddressSpace()) {
5056 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5057 D.setInvalidType();
5058 }
5059 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005060 }
5061
Larisse Voufo39a1e502013-08-06 01:03:05 +00005062 bool IsExplicitSpecialization = false;
5063 bool IsVariableTemplateSpecialization = false;
5064 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005065 bool IsVariableTemplate = false;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005066 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005067 VarDecl *NewVD = 0;
5068 VarTemplateDecl *NewTemplate = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005069 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005070 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005071 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005072 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005073
5074 if (D.isInvalidType())
5075 NewVD->setInvalidDecl();
5076 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005077 bool Invalid = false;
5078
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005079 if (DC->isRecord() && !CurContext->isRecord()) {
5080 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005081 switch (SC) {
5082 case SC_None:
5083 break;
5084 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005085 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5086 diag::err_static_out_of_line)
5087 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005088 break;
5089 case SC_Auto:
5090 case SC_Register:
5091 case SC_Extern:
5092 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5093 // to names of variables declared in a block or to function parameters.
5094 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5095 // of class members
5096
5097 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5098 diag::err_storage_class_for_static_member)
5099 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5100 break;
5101 case SC_PrivateExtern:
5102 llvm_unreachable("C storage class in c++!");
5103 case SC_OpenCLWorkGroupLocal:
5104 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005105 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005106 }
5107
Richard Smith42973752012-02-16 20:41:22 +00005108 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005109 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5110 if (RD->isLocalClass())
5111 Diag(D.getIdentifierLoc(),
5112 diag::err_static_data_member_not_allowed_in_local_class)
5113 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005114
Richard Smith42973752012-02-16 20:41:22 +00005115 // C++98 [class.union]p1: If a union contains a static data member,
5116 // the program is ill-formed. C++11 drops this restriction.
5117 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005118 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005119 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005120 ? diag::warn_cxx98_compat_static_data_member_in_union
5121 : diag::ext_static_data_member_in_union) << Name;
5122 // We conservatively disallow static data members in anonymous structs.
5123 else if (!RD->getDeclName())
5124 Diag(D.getIdentifierLoc(),
5125 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005126 << Name << RD->isUnion();
5127 }
5128 }
5129
Larisse Voufo39a1e502013-08-06 01:03:05 +00005130 NamedDecl *PrevDecl = 0;
5131 if (Previous.begin() != Previous.end())
5132 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5133 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5134
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005135 // Match up the template parameter lists with the scope specifier, then
5136 // determine whether we have a template or a template specialization.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005137 TemplateParameterList *TemplateParams =
5138 MatchTemplateParametersToScopeSpecifier(
5139 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5140 D.getCXXScopeSpec(), TemplateParamLists,
5141 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005142 if (TemplateParams) {
5143 if (!TemplateParams->size() &&
5144 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005145 // There is an extraneous 'template<>' for this variable. Complain
5146 // about it, but allow the declaration of the variable.
5147 Diag(TemplateParams->getTemplateLoc(),
5148 diag::err_template_variable_noparams)
5149 << II
5150 << SourceRange(TemplateParams->getTemplateLoc(),
5151 TemplateParams->getRAngleLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005152 } else {
5153 // Only C++1y supports variable templates (N3651).
5154 Diag(D.getIdentifierLoc(),
5155 getLangOpts().CPlusPlus1y
5156 ? diag::warn_cxx11_compat_variable_template
5157 : diag::ext_variable_template);
5158
5159 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5160 // This is an explicit specialization or a partial specialization.
5161 // Check that we can declare a specialization here
5162
5163 IsVariableTemplateSpecialization = true;
5164 IsPartialSpecialization = TemplateParams->size() > 0;
5165
5166 } else { // if (TemplateParams->size() > 0)
Larisse Voufo21de36b2013-08-06 03:43:07 +00005167 // This is a template declaration.
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005168 IsVariableTemplate = true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005169
5170 // Check that we can declare a template here.
5171 if (CheckTemplateDeclScope(S, TemplateParams))
5172 return 0;
5173
5174 // If there is a previous declaration with the same name, check
5175 // whether this is a valid redeclaration.
5176 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5177 PrevDecl = PrevVarTemplate = 0;
5178
5179 if (PrevVarTemplate) {
5180 // Ensure that the template parameter lists are compatible.
5181 if (!TemplateParameterListsAreEqual(
5182 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5183 /*Complain=*/true, TPL_TemplateMatch))
5184 return 0;
5185 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5186 // Maybe we will complain about the shadowed template parameter.
5187 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5188
5189 // Just pretend that we didn't see the previous declaration.
5190 PrevDecl = 0;
5191 } else if (PrevDecl) {
5192 // C++ [temp]p5:
5193 // ... a template name declared in namespace scope or in class
5194 // scope shall be unique in that scope.
5195 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5196 << Name;
5197 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5198 return 0;
5199 }
5200
5201 // Check the template parameter list of this declaration, possibly
5202 // merging in the template parameter list from the previous variable
5203 // template declaration.
5204 if (CheckTemplateParameterList(
5205 TemplateParams,
5206 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5207 : 0,
5208 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5209 DC->isDependentContext())
5210 ? TPC_ClassTemplateMember
5211 : TPC_VarTemplate))
5212 Invalid = true;
5213
5214 if (D.getCXXScopeSpec().isSet()) {
5215 // If the name of the template was qualified, we must be defining
5216 // the template out-of-line.
5217 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5218 !PrevVarTemplate) {
Richard Smith114394f2013-08-09 04:35:01 +00005219 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5220 << Name << DC << /*IsDefinition*/true
5221 << D.getCXXScopeSpec().getRange();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005222 Invalid = true;
5223 }
5224 }
5225 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005226 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005227 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5228 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5229
5230 // We have encountered something that the user meant to be a
5231 // specialization (because it has explicitly-specified template
5232 // arguments) but that was not introduced with a "template<>" (or had
5233 // too few of them).
5234 // FIXME: Differentiate between attempts for explicit instantiations
5235 // (starting with "template") and the rest.
5236 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5237 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5238 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5239 "template<> ");
5240 IsVariableTemplateSpecialization = true;
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005241 }
Mike Stump11289f42009-09-09 15:08:12 +00005242
Larisse Voufo39a1e502013-08-06 01:03:05 +00005243 if (IsVariableTemplateSpecialization) {
5244 if (!PrevVarTemplate) {
5245 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5246 << IsPartialSpecialization;
5247 return 0;
5248 }
5249
5250 SourceLocation TemplateKWLoc =
5251 TemplateParamLists.size() > 0
5252 ? TemplateParamLists[0]->getTemplateLoc()
5253 : SourceLocation();
5254 DeclResult Res = ActOnVarTemplateSpecialization(
5255 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5256 IsPartialSpecialization);
5257 if (Res.isInvalid())
5258 return 0;
5259 NewVD = cast<VarDecl>(Res.get());
5260 AddToScope = false;
5261 } else
5262 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5263 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005264
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005265 // If this is supposed to be a variable template, create it as such.
5266 if (IsVariableTemplate) {
5267 NewTemplate =
5268 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5269 TemplateParams, NewVD, PrevVarTemplate);
5270 NewVD->setDescribedVarTemplate(NewTemplate);
5271 }
5272
Richard Smithb2bc2e62011-02-21 20:05:19 +00005273 // If this decl has an auto type in need of deduction, make a note of the
5274 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005275 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005276 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005277
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005278 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005279 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005280 if (NewTemplate)
5281 NewTemplate->setInvalidDecl();
5282 }
Mike Stump11289f42009-09-09 15:08:12 +00005283
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005284 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005285
Larisse Voufo39a1e502013-08-06 01:03:05 +00005286 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5287 if (TemplateParams && TemplateParamLists.size() > 1 &&
5288 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5289 NewVD->setTemplateParameterListsInfo(
5290 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5291 } else if (IsVariableTemplateSpecialization ||
5292 (!TemplateParams && TemplateParamLists.size() > 0 &&
5293 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005294 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00005295 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005296 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005297 }
Richard Smitha77a0a62011-08-15 21:04:07 +00005298
Richard Smith6331c402012-02-13 22:16:19 +00005299 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005300 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005301 }
5302
Douglas Gregor41866812011-09-12 18:37:38 +00005303 // Set the lexical context. If the declarator has a C++ scope specifier, the
5304 // lexical context will be different from the semantic context.
5305 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005306 if (NewTemplate)
5307 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005308
Richard Smith541b38b2013-09-20 01:15:31 +00005309 if (IsLocalExternDecl)
5310 NewVD->setLocalExternDecl();
5311
Richard Smithb4a9e862013-04-12 22:46:28 +00005312 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005313 if (NewVD->hasLocalStorage()) {
5314 // C++11 [dcl.stc]p4:
5315 // When thread_local is applied to a variable of block scope the
5316 // storage-class-specifier static is implied if it does not appear
5317 // explicitly.
5318 // Core issue: 'static' is not implied if the variable is declared
5319 // 'extern'.
5320 if (SCSpec == DeclSpec::SCS_unspecified &&
5321 TSCS == DeclSpec::TSCS_thread_local &&
5322 DC->isFunctionOrMethod())
5323 NewVD->setTSCSpec(TSCS);
5324 else
5325 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5326 diag::err_thread_non_global)
5327 << DeclSpec::getSpecifierName(TSCS);
5328 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005329 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5330 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005331 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005332 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005333 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005334
John McCallc87d9722013-04-02 02:48:58 +00005335 // C99 6.7.4p3
5336 // An inline definition of a function with external linkage shall
5337 // not contain a definition of a modifiable object with static or
5338 // thread storage duration...
5339 // We only apply this when the function is required to be defined
5340 // elsewhere, i.e. when the function is not 'extern inline'. Note
5341 // that a local variable with thread storage duration still has to
5342 // be marked 'static'. Also note that it's possible to get these
5343 // semantics in C++ using __attribute__((gnu_inline)).
5344 if (SC == SC_Static && S->getFnParent() != 0 &&
5345 !NewVD->getType().isConstQualified()) {
5346 FunctionDecl *CurFD = getCurFunctionDecl();
5347 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5348 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5349 diag::warn_static_local_in_extern_inline);
5350 MaybeSuggestAddingStaticToDecl(CurFD);
5351 }
5352 }
5353
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005354 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005355 if (IsVariableTemplateSpecialization)
5356 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5357 << (IsPartialSpecialization ? 1 : 0)
5358 << FixItHint::CreateRemoval(
5359 D.getDeclSpec().getModulePrivateSpecLoc());
5360 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005361 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5362 << 2
5363 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005364 else if (NewVD->hasLocalStorage())
5365 Diag(NewVD->getLocation(), diag::err_module_private_local)
5366 << 0 << NewVD->getDeclName()
5367 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5368 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005369 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005370 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005371 if (NewTemplate)
5372 NewTemplate->setModulePrivate();
5373 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005374 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005375
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005376 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005377 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005378
Richard Smith848e1f12013-02-01 08:12:08 +00005379 if (NewVD->hasAttrs())
5380 CheckAlignasUnderalignment(NewVD);
5381
Peter Collingbournec6b08572012-08-28 20:37:50 +00005382 if (getLangOpts().CUDA) {
5383 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5384 // storage [duration]."
5385 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005386 (NewVD->hasAttr<CUDASharedAttr>() ||
5387 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005388 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005389 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005390 }
5391
John McCall31168b02011-06-15 23:02:42 +00005392 // In auto-retain/release, infer strong retension for variables of
5393 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005394 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005395 NewVD->setInvalidDecl();
5396
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005397 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005398 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005399 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005400 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005401 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005402 if (S->getFnParent() != 0) {
5403 switch (SC) {
5404 case SC_None:
5405 case SC_Auto:
5406 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5407 break;
5408 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005409 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005410 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5411 break;
5412 case SC_Static:
5413 case SC_Extern:
5414 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005415 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005416 break;
5417 }
5418 }
5419
5420 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00005421 Context, Label));
David Chisnall0867d9c2012-02-18 16:12:34 +00005422 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5423 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5424 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5425 if (I != ExtnameUndeclaredIdentifiers.end()) {
5426 NewVD->addAttr(I->second);
5427 ExtnameUndeclaredIdentifiers.erase(I);
5428 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005429 }
5430
John McCalla2a3f7d2010-03-16 21:48:18 +00005431 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005432 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005433 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005434
John McCall1f82f242009-11-18 22:49:29 +00005435 // Don't consider existing declarations that are in a different
5436 // scope and are out-of-semantic-context declarations (if the new
5437 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005438 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5439 D.getCXXScopeSpec().isNotEmpty() ||
5440 IsExplicitSpecialization ||
5441 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005442
Richard Smith1c34fb72013-08-13 18:18:50 +00005443 // Check whether the previous declaration is in the same block scope. This
5444 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5445 if (getLangOpts().CPlusPlus &&
5446 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5447 NewVD->setPreviousDeclInSameBlockScope(
5448 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005449 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005450
David Blaikiebbafb8a2012-03-11 07:00:24 +00005451 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005452 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5453 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005454 // Merge the decl with the existing one if appropriate.
5455 if (!Previous.empty()) {
5456 if (Previous.isSingleResult() &&
5457 isa<FieldDecl>(Previous.getFoundDecl()) &&
5458 D.getCXXScopeSpec().isSet()) {
5459 // The user tried to define a non-static data member
5460 // out-of-line (C++ [dcl.meaning]p1).
5461 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5462 << D.getCXXScopeSpec().getRange();
5463 Previous.clear();
5464 NewVD->setInvalidDecl();
5465 }
5466 } else if (D.getCXXScopeSpec().isSet()) {
5467 // No previous declaration in the qualifying scope.
5468 Diag(D.getIdentifierLoc(), diag::err_no_member)
5469 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005470 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005471 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005472 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005473
Larisse Voufo39a1e502013-08-06 01:03:05 +00005474 if (!IsVariableTemplateSpecialization) {
5475 if (PrevVarTemplate) {
5476 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5477 LookupOrdinaryName, ForRedeclaration);
5478 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005479 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufo39a1e502013-08-06 01:03:05 +00005480 } else
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005481 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufo39a1e502013-08-06 01:03:05 +00005482 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005483
5484 // This is an explicit specialization of a static data member. Check it.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005485 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005486 CheckMemberSpecialization(NewVD, Previous))
5487 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005488 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005489
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005490 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005491 checkAttributesAfterMerging(*this, *NewVD);
5492
Richard Smithac974a32013-06-30 09:48:50 +00005493 // If this is the first declaration of an extern C variable, update
5494 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005495 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005496 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005497 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005498
Reid Klecknerd8110b62013-09-10 20:14:30 +00005499 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005500 Decl *ManglingContextDecl;
5501 if (MangleNumberingContext *MCtx =
5502 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5503 ManglingContextDecl)) {
5504 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5505 }
5506 }
5507
Larisse Voufo39a1e502013-08-06 01:03:05 +00005508 // If we are providing an explicit specialization of a static variable
5509 // template, make a note of that.
5510 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo4cda4612013-08-22 00:28:27 +00005511 PrevVarTemplate->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005512
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005513 if (NewTemplate) {
5514 ActOnDocumentableDecl(NewTemplate);
5515 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005516 }
5517
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005518 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005519}
5520
John McCalldf8b37c2010-03-22 09:20:08 +00005521/// \brief Diagnose variable or built-in function shadowing. Implements
5522/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005523///
John McCalldf8b37c2010-03-22 09:20:08 +00005524/// This method is called whenever a VarDecl is added to a "useful"
5525/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005526///
John McCall2d8c7602010-03-20 04:12:52 +00005527/// \param S the scope in which the shadowing name is being declared
5528/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005529///
John McCalldf8b37c2010-03-22 09:20:08 +00005530void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005531 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005532 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005533 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005534 return;
5535
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005536 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005537 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005538 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005539
5540 DeclContext *NewDC = D->getDeclContext();
5541
John McCall2d8c7602010-03-20 04:12:52 +00005542 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005543 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005544 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005545
John McCalla2a3f7d2010-03-16 21:48:18 +00005546 NamedDecl* ShadowedDecl = R.getFoundDecl();
5547 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5548 return;
5549
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005550 // Fields are not shadowed by variables in C++ static methods.
5551 if (isa<FieldDecl>(ShadowedDecl))
5552 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5553 if (MD->isStatic())
5554 return;
5555
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005556 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5557 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005558 // For shadowing external vars, make sure that we point to the global
5559 // declaration, not a locally scoped extern declaration.
5560 for (VarDecl::redecl_iterator
5561 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5562 I != E; ++I)
5563 if (I->isFileVarDecl()) {
5564 ShadowedDecl = *I;
5565 break;
5566 }
5567 }
5568
5569 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5570
John McCall2d8c7602010-03-20 04:12:52 +00005571 // Only warn about certain kinds of shadowing for class members.
5572 if (NewDC && NewDC->isRecord()) {
5573 // In particular, don't warn about shadowing non-class members.
5574 if (!OldDC->isRecord())
5575 return;
5576
5577 // TODO: should we warn about static data members shadowing
5578 // static data members from base classes?
5579
5580 // TODO: don't diagnose for inaccessible shadowed members.
5581 // This is hard to do perfectly because we might friend the
5582 // shadowing context, but that's just a false negative.
5583 }
5584
5585 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005586 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005587 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005588 if (isa<FieldDecl>(ShadowedDecl))
5589 Kind = 3; // field
5590 else
5591 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005592 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005593 Kind = 1; // global
5594 else
5595 Kind = 0; // local
5596
John McCall2d8c7602010-03-20 04:12:52 +00005597 DeclarationName Name = R.getLookupName();
5598
John McCalla2a3f7d2010-03-16 21:48:18 +00005599 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005600 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5601 return;
John McCall2d8c7602010-03-20 04:12:52 +00005602 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005603 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5604}
5605
John McCalldf8b37c2010-03-22 09:20:08 +00005606/// \brief Check -Wshadow without the advantage of a previous lookup.
5607void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005608 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005609 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005610 return;
5611
John McCalldf8b37c2010-03-22 09:20:08 +00005612 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5613 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5614 LookupName(R, S);
5615 CheckShadow(S, D, R);
5616}
5617
Richard Smithac974a32013-06-30 09:48:50 +00005618/// Check for conflict between this global or extern "C" declaration and
5619/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005620template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005621static bool checkGlobalOrExternCConflict(
5622 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5623 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5624 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005625
Richard Smithac974a32013-06-30 09:48:50 +00005626 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5627 // The common case: this global doesn't conflict with any extern "C"
5628 // declaration.
5629 return false;
5630 }
5631
5632 if (Prev) {
5633 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5634 // Both the old and new declarations have C language linkage. This is a
5635 // redeclaration.
5636 Previous.clear();
5637 Previous.addDecl(Prev);
5638 return true;
5639 }
5640
5641 // This is a global, non-extern "C" declaration, and there is a previous
5642 // non-global extern "C" declaration. Diagnose if this is a variable
5643 // declaration.
5644 if (!isa<VarDecl>(ND))
5645 return false;
5646 } else {
5647 // The declaration is extern "C". Check for any declaration in the
5648 // translation unit which might conflict.
5649 if (IsGlobal) {
5650 // We have already performed the lookup into the translation unit.
5651 IsGlobal = false;
5652 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5653 I != E; ++I) {
5654 if (isa<VarDecl>(*I)) {
5655 Prev = *I;
5656 break;
5657 }
5658 }
5659 } else {
5660 DeclContext::lookup_result R =
5661 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5662 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5663 I != E; ++I) {
5664 if (isa<VarDecl>(*I)) {
5665 Prev = *I;
5666 break;
5667 }
5668 // FIXME: If we have any other entity with this name in global scope,
5669 // the declaration is ill-formed, but that is a defect: it breaks the
5670 // 'stat' hack, for instance. Only variables can have mangled name
5671 // clashes with extern "C" declarations, so only they deserve a
5672 // diagnostic.
5673 }
5674 }
5675
5676 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005677 return false;
5678 }
5679
Richard Smithac974a32013-06-30 09:48:50 +00005680 // Use the first declaration's location to ensure we point at something which
5681 // is lexically inside an extern "C" linkage-spec.
5682 assert(Prev && "should have found a previous declaration to diagnose");
5683 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005684 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005685 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005686 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005687
5688 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5689 << IsGlobal << ND;
5690 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5691 << IsGlobal;
5692 return false;
5693}
5694
5695/// Apply special rules for handling extern "C" declarations. Returns \c true
5696/// if we have found that this is a redeclaration of some prior entity.
5697///
5698/// Per C++ [dcl.link]p6:
5699/// Two declarations [for a function or variable] with C language linkage
5700/// with the same name that appear in different scopes refer to the same
5701/// [entity]. An entity with C language linkage shall not be declared with
5702/// the same name as an entity in global scope.
5703template<typename T>
5704static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5705 LookupResult &Previous) {
5706 if (!S.getLangOpts().CPlusPlus) {
5707 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005708 // variable declared in function scope. We don't need this in C++, because
5709 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005710 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5711 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5712 Previous.clear();
5713 Previous.addDecl(Prev);
5714 return true;
5715 }
5716 }
5717 return false;
5718 }
5719
5720 // A declaration in the translation unit can conflict with an extern "C"
5721 // declaration.
5722 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5723 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5724
5725 // An extern "C" declaration can conflict with a declaration in the
5726 // translation unit or can be a redeclaration of an extern "C" declaration
5727 // in another scope.
5728 if (isIncompleteDeclExternC(S,ND))
5729 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5730
5731 // Neither global nor extern "C": nothing to do.
5732 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005733}
5734
Richard Smith27d807c2013-04-30 13:56:41 +00005735void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005736 // If the decl is already known invalid, don't check it.
5737 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005738 return;
Mike Stump11289f42009-09-09 15:08:12 +00005739
Abramo Bagnara341ab732012-11-08 14:44:42 +00005740 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5741 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005742
Richard Smith27d807c2013-04-30 13:56:41 +00005743 // Defer checking an 'auto' type until its initializer is attached.
5744 if (T->isUndeducedType())
5745 return;
5746
John McCall8b07ec22010-05-15 11:32:37 +00005747 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005748 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5749 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005750 T = Context.getObjCObjectPointerType(T);
5751 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005752 }
Mike Stump11289f42009-09-09 15:08:12 +00005753
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005754 // Emit an error if an address space was applied to decl with local storage.
5755 // This includes arrays of objects with address space qualifiers, but not
5756 // automatic variables that point to other address spaces.
5757 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005758 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005759 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005760 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005761 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005762 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005763
Tanya Lattner713eef42013-04-05 20:14:50 +00005764 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5765 // __constant address space.
5766 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5767 && T.getAddressSpace() != LangAS::opencl_constant
5768 && !T->isSamplerT()){
5769 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5770 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005771 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005772 }
5773
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005774 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5775 // scope.
5776 if ((getLangOpts().OpenCLVersion >= 120)
5777 && NewVD->isStaticLocal()) {
5778 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5779 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005780 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005781 }
5782
Mike Stumpca5ae662009-04-14 00:57:29 +00005783 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005784 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005785 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005786 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005787 else {
5788 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005789 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005790 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005791 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005792
Chris Lattner9fecd742009-04-19 05:21:20 +00005793 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005794 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005795 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005796 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005797
Chris Lattner9fecd742009-04-19 05:21:20 +00005798 if ((isVM && NewVD->hasLinkage()) ||
5799 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005800 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005801 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005802 TypeSourceInfo *FixedTInfo =
5803 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5804 SizeIsNegative, Oversized);
5805 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005806 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005807 // FIXME: This won't give the correct result for
5808 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005809 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005810
Anders Carlsson6c885802009-02-28 21:56:50 +00005811 if (NewVD->isFileVarDecl())
5812 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005813 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005814 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005815 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005816 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005817 else
5818 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005819 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005820 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005821 return;
Mike Stump11289f42009-09-09 15:08:12 +00005822 }
5823
Abramo Bagnara341ab732012-11-08 14:44:42 +00005824 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005825 if (NewVD->isFileVarDecl())
5826 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5827 else
5828 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005829 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005830 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005831 }
Mike Stump11289f42009-09-09 15:08:12 +00005832
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005833 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005834 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005835 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005836 }
5837
David Majnemer0ffa3312013-05-29 00:56:45 +00005838 if (T->isVoidType()) {
5839 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5840 // of objects and functions.
5841 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5842 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5843 << T;
5844 NewVD->setInvalidDecl();
5845 return;
5846 }
Richard Smith27d807c2013-04-30 13:56:41 +00005847 }
5848
5849 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5850 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5851 NewVD->setInvalidDecl();
5852 return;
5853 }
5854
5855 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5856 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5857 NewVD->setInvalidDecl();
5858 return;
5859 }
5860
5861 if (NewVD->isConstexpr() && !T->isDependentType() &&
5862 RequireLiteralType(NewVD->getLocation(), T,
5863 diag::err_constexpr_var_non_literal)) {
5864 // Can't perform this check until the type is deduced.
5865 NewVD->setInvalidDecl();
5866 return;
5867 }
5868}
5869
5870/// \brief Perform semantic checking on a newly-created variable
5871/// declaration.
5872///
5873/// This routine performs all of the type-checking required for a
5874/// variable declaration once it has been built. It is used both to
5875/// check variables after they have been parsed and their declarators
5876/// have been translated into a declaration, and to check variables
5877/// that have been instantiated from a template.
5878///
5879/// Sets NewVD->isInvalidDecl() if an error was encountered.
5880///
5881/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005882bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005883 CheckVariableDeclarationType(NewVD);
5884
5885 // If the decl is already known invalid, don't check it.
5886 if (NewVD->isInvalidDecl())
5887 return false;
5888
John McCallb65e8fe2013-04-01 18:34:28 +00005889 // If we did not find anything by this name, look for a non-visible
5890 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005891 if (Previous.empty() &&
5892 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005893 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005894
Douglas Gregor3552dab2013-01-09 00:47:56 +00005895 // Filter out any non-conflicting previous declarations.
5896 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5897
John McCall1f82f242009-11-18 22:49:29 +00005898 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005899 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005900 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005901 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005902 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005903}
5904
Douglas Gregor36d1b142009-10-06 17:59:45 +00005905/// \brief Data used with FindOverriddenMethod
5906struct FindOverriddenMethodData {
5907 Sema *S;
5908 CXXMethodDecl *Method;
5909};
5910
5911/// \brief Member lookup function that determines whether a given C++
5912/// method overrides a method in a base class, to be used with
5913/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005914static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005915 CXXBasePath &Path,
5916 void *UserData) {
5917 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005918
Douglas Gregor36d1b142009-10-06 17:59:45 +00005919 FindOverriddenMethodData *Data
5920 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005921
5922 DeclarationName Name = Data->Method->getDeclName();
5923
5924 // FIXME: Do we care about other names here too?
5925 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005926 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005927 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5928 CanQualType CT = Data->S->Context.getCanonicalType(T);
5929
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005930 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005931 }
5932
5933 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005934 !Path.Decls.empty();
5935 Path.Decls = Path.Decls.slice(1)) {
5936 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005937 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5938 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005939 return true;
5940 }
5941 }
5942
5943 return false;
5944}
5945
David Blaikie7e414262012-10-17 00:47:58 +00005946namespace {
5947 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5948}
5949/// \brief Report an error regarding overriding, along with any relevant
5950/// overriden methods.
5951///
5952/// \param DiagID the primary error to report.
5953/// \param MD the overriding method.
5954/// \param OEK which overrides to include as notes.
5955static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5956 OverrideErrorKind OEK = OEK_All) {
5957 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5958 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5959 E = MD->end_overridden_methods();
5960 I != E; ++I) {
5961 // This check (& the OEK parameter) could be replaced by a predicate, but
5962 // without lambdas that would be overkill. This is still nicer than writing
5963 // out the diag loop 3 times.
5964 if ((OEK == OEK_All) ||
5965 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5966 (OEK == OEK_Deleted && (*I)->isDeleted()))
5967 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5968 }
5969}
5970
Sebastian Redld5b24532009-11-18 21:51:29 +00005971/// AddOverriddenMethods - See if a method overrides any in the base classes,
5972/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005973bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00005974 // Look for virtual methods in base classes that this method might override.
5975 CXXBasePaths Paths;
5976 FindOverriddenMethodData Data;
5977 Data.Method = MD;
5978 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00005979 bool hasDeletedOverridenMethods = false;
5980 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005981 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00005982 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5983 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5984 E = Paths.found_decls_end(); I != E; ++I) {
5985 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00005986 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00005987 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00005988 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00005989 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00005990 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00005991 hasDeletedOverridenMethods |= OldMD->isDeleted();
5992 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005993 AddedAny = true;
5994 }
Sebastian Redld5b24532009-11-18 21:51:29 +00005995 }
5996 }
5997 }
David Blaikie7e414262012-10-17 00:47:58 +00005998
5999 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6000 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6001 }
6002 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6003 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6004 }
6005
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006006 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00006007}
6008
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006009namespace {
6010 // Struct for holding all of the extra arguments needed by
6011 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6012 struct ActOnFDArgs {
6013 Scope *S;
6014 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006015 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006016 bool AddToScope;
6017 };
6018}
6019
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006020namespace {
6021
6022// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006023// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006024class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6025 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006026 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6027 CXXRecordDecl *Parent)
6028 : Context(Context), OriginalFD(TypoFD),
6029 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006030
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006031 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006032 if (candidate.getEditDistance() == 0)
6033 return false;
6034
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006035 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006036 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6037 CDeclEnd = candidate.end();
6038 CDecl != CDeclEnd; ++CDecl) {
6039 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6040
6041 if (FD && !FD->hasBody() &&
6042 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6043 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6044 CXXRecordDecl *Parent = MD->getParent();
6045 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6046 return true;
6047 } else if (!ExpectedParent) {
6048 return true;
6049 }
6050 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006051 }
6052
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006053 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006054 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006055
6056 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006057 ASTContext &Context;
6058 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006059 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006060};
6061
6062}
6063
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006064/// \brief Generate diagnostics for an invalid function redeclaration.
6065///
6066/// This routine handles generating the diagnostic messages for an invalid
6067/// function redeclaration, including finding possible similar declarations
6068/// or performing typo correction if there are no previous declarations with
6069/// the same name.
6070///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006071/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006072/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006073static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006074 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006075 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006076 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006077 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006078 SmallVector<unsigned, 1> MismatchedParams;
6079 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006080 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006081 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006082 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6083 : diag::err_member_decl_does_not_match;
6084 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6085 IsLocalFriend ? Sema::LookupLocalFriendName
6086 : Sema::LookupOrdinaryName,
6087 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006088
6089 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006090 if (IsLocalFriend)
6091 SemaRef.LookupName(Prev, S);
6092 else
6093 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006094 assert(!Prev.isAmbiguous() &&
6095 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006096 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006097 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6098 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006099 if (!Prev.empty()) {
6100 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6101 Func != FuncEnd; ++Func) {
6102 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006103 if (FD &&
6104 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006105 // Add 1 to the index so that 0 can mean the mismatch didn't
6106 // involve a parameter
6107 unsigned ParamNum =
6108 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6109 NearMatches.push_back(std::make_pair(FD, ParamNum));
6110 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006111 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006112 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006113 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006114 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6115 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6116 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006117 // Set up everything for the call to ActOnFunctionDeclarator
6118 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6119 ExtraArgs.D.getIdentifierLoc());
6120 Previous.clear();
6121 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006122 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6123 CDeclEnd = Correction.end();
6124 CDecl != CDeclEnd; ++CDecl) {
6125 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006126 if (FD && !FD->hasBody() &&
6127 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006128 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006129 }
6130 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006131 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006132
6133 NamedDecl *Result;
6134 // Retry building the function declaration with the new previous
6135 // declarations, and with errors suppressed.
6136 {
6137 // Trap errors.
6138 Sema::SFINAETrap Trap(SemaRef);
6139
6140 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6141 // pieces need to verify the typo-corrected C++ declaration and hopefully
6142 // eliminate the need for the parameter pack ExtraArgs.
6143 Result = SemaRef.ActOnFunctionDeclarator(
6144 ExtraArgs.S, ExtraArgs.D,
6145 Correction.getCorrectionDecl()->getDeclContext(),
6146 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6147 ExtraArgs.AddToScope);
6148
6149 if (Trap.hasErrorOccurred())
6150 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006151 }
Richard Smithf9b15102013-08-17 00:46:16 +00006152
6153 if (Result) {
6154 // Determine which correction we picked.
6155 Decl *Canonical = Result->getCanonicalDecl();
6156 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6157 I != E; ++I)
6158 if ((*I)->getCanonicalDecl() == Canonical)
6159 Correction.setCorrectionDecl(*I);
6160
6161 SemaRef.diagnoseTypo(
6162 Correction,
6163 SemaRef.PDiag(IsLocalFriend
6164 ? diag::err_no_matching_local_friend_suggest
6165 : diag::err_member_decl_does_not_match_suggest)
6166 << Name << NewDC << IsDefinition);
6167 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006168 }
Richard Smithf9b15102013-08-17 00:46:16 +00006169
6170 // Pretend the typo correction never occurred
6171 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6172 ExtraArgs.D.getIdentifierLoc());
6173 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6174 Previous.clear();
6175 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006176 }
6177
Richard Smithf9b15102013-08-17 00:46:16 +00006178 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6179 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006180
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006181 bool NewFDisConst = false;
6182 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006183 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006184
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006185 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006186 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6187 NearMatch != NearMatchEnd; ++NearMatch) {
6188 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6190 bool FDisConst = MD && MD->isConst();
6191 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006192
Richard Smith541b38b2013-09-20 01:15:31 +00006193 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006194 if (unsigned Idx = NearMatch->second) {
6195 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006196 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6197 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006198 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6199 : diag::note_local_decl_close_param_match)
6200 << Idx << FDParam->getType()
6201 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006202 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006203 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006204 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006205 } else
Richard Smith114394f2013-08-09 04:35:01 +00006206 SemaRef.Diag(FD->getLocation(),
6207 IsMember ? diag::note_member_def_close_match
6208 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006209 }
Richard Smithf9b15102013-08-17 00:46:16 +00006210 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006211}
6212
David Blaikie30d15442011-10-19 22:56:21 +00006213static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6214 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006215 switch (D.getDeclSpec().getStorageClassSpec()) {
6216 default: llvm_unreachable("Unknown storage class!");
6217 case DeclSpec::SCS_auto:
6218 case DeclSpec::SCS_register:
6219 case DeclSpec::SCS_mutable:
6220 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6221 diag::err_typecheck_sclass_func);
6222 D.setInvalidType();
6223 break;
6224 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006225 case DeclSpec::SCS_extern:
6226 if (D.getDeclSpec().isExternInLinkageSpec())
6227 return SC_None;
6228 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006229 case DeclSpec::SCS_static: {
6230 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6231 // C99 6.7.1p5:
6232 // The declaration of an identifier for a function that has
6233 // block scope shall have no explicit storage-class specifier
6234 // other than extern
6235 // See also (C++ [dcl.stc]p4).
6236 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6237 diag::err_static_block_func);
6238 break;
6239 } else
6240 return SC_Static;
6241 }
6242 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6243 }
6244
6245 // No explicit storage class has already been returned
6246 return SC_None;
6247}
6248
6249static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6250 DeclContext *DC, QualType &R,
6251 TypeSourceInfo *TInfo,
6252 FunctionDecl::StorageClass SC,
6253 bool &IsVirtualOkay) {
6254 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6255 DeclarationName Name = NameInfo.getName();
6256
6257 FunctionDecl *NewFD = 0;
6258 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006259
David Blaikiebbafb8a2012-03-11 07:00:24 +00006260 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006261 // Determine whether the function was written with a
6262 // prototype. This true when:
6263 // - there is a prototype in the declarator, or
6264 // - the type R of the function is some kind of typedef or other reference
6265 // to a type name (which eventually refers to a function type).
6266 bool HasPrototype =
6267 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6268 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6269
David Blaikie30d15442011-10-19 22:56:21 +00006270 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006271 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006272 TInfo, SC, isInline,
6273 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006274 if (D.isInvalidType())
6275 NewFD->setInvalidDecl();
6276
6277 // Set the lexical context.
6278 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6279
6280 return NewFD;
6281 }
6282
6283 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6284 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6285
6286 // Check that the return type is not an abstract class type.
6287 // For record types, this is done by the AbstractClassUsageDiagnoser once
6288 // the class has been completely parsed.
6289 if (!DC->isRecord() &&
6290 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6291 R->getAs<FunctionType>()->getResultType(),
6292 diag::err_abstract_type_in_decl,
6293 SemaRef.AbstractReturnType))
6294 D.setInvalidType();
6295
6296 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6297 // This is a C++ constructor declaration.
6298 assert(DC->isRecord() &&
6299 "Constructors can only be declared in a member context");
6300
6301 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6302 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006303 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006304 R, TInfo, isExplicit, isInline,
6305 /*isImplicitlyDeclared=*/false,
6306 isConstexpr);
6307
6308 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6309 // This is a C++ destructor declaration.
6310 if (DC->isRecord()) {
6311 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6312 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6313 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6314 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006315 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006316 NameInfo, R, TInfo, isInline,
6317 /*isImplicitlyDeclared=*/false);
6318
6319 // If the class is complete, then we now create the implicit exception
6320 // specification. If the class is incomplete or dependent, we can't do
6321 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006322 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006323 Record->getDefinition() && !Record->isBeingDefined() &&
6324 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6325 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6326 }
6327
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006328 // The Microsoft ABI requires that we perform the destructor body
6329 // checks (i.e. operator delete() lookup) at every declaration, as
6330 // any translation unit may need to emit a deleting destructor.
6331 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6332 !Record->isDependentType() && Record->getDefinition() &&
Hans Wennborge955e392013-12-17 17:49:22 +00006333 !Record->isBeingDefined() && !NewDD->isDeleted()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006334 SemaRef.CheckDestructor(NewDD);
6335 }
6336
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006337 IsVirtualOkay = true;
6338 return NewDD;
6339
6340 } else {
6341 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6342 D.setInvalidType();
6343
6344 // Create a FunctionDecl to satisfy the function definition parsing
6345 // code path.
6346 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006347 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006348 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006349 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006350 /*hasPrototype=*/true, isConstexpr);
6351 }
6352
6353 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6354 if (!DC->isRecord()) {
6355 SemaRef.Diag(D.getIdentifierLoc(),
6356 diag::err_conv_function_not_member);
6357 return 0;
6358 }
6359
6360 SemaRef.CheckConversionDeclarator(D, R, SC);
6361 IsVirtualOkay = true;
6362 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006363 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006364 R, TInfo, isInline, isExplicit,
6365 isConstexpr, SourceLocation());
6366
6367 } else if (DC->isRecord()) {
6368 // If the name of the function is the same as the name of the record,
6369 // then this must be an invalid constructor that has a return type.
6370 // (The parser checks for a return type and makes the declarator a
6371 // constructor if it has no return type).
6372 if (Name.getAsIdentifierInfo() &&
6373 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6374 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6375 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6376 << SourceRange(D.getIdentifierLoc());
6377 return 0;
6378 }
6379
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006380 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006381 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6382 cast<CXXRecordDecl>(DC),
6383 D.getLocStart(), NameInfo, R,
6384 TInfo, SC, isInline,
6385 isConstexpr, SourceLocation());
6386 IsVirtualOkay = !Ret->isStatic();
6387 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006388 } else {
6389 // Determine whether the function was written with a
6390 // prototype. This true when:
6391 // - we're in C++ (where every function has a prototype),
6392 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006393 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006394 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006395 true/*HasPrototype*/, isConstexpr);
6396 }
6397}
6398
Eli Friedman8f5e9832012-09-20 01:40:23 +00006399void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6400 // In C++, the empty parameter-type-list must be spelled "void"; a
6401 // typedef of void is not permitted.
6402 if (getLangOpts().CPlusPlus &&
6403 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6404 bool IsTypeAlias = false;
6405 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6406 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6407 else if (const TemplateSpecializationType *TST =
6408 Param->getType()->getAs<TemplateSpecializationType>())
6409 IsTypeAlias = TST->isTypeAlias();
6410 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6411 << IsTypeAlias;
6412 }
6413}
6414
Matt Arsenaultefb38192013-07-23 01:23:36 +00006415enum OpenCLParamType {
6416 ValidKernelParam,
6417 PtrPtrKernelParam,
6418 PtrKernelParam,
6419 InvalidKernelParam,
6420 RecordKernelParam
6421};
6422
6423static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6424 if (PT->isPointerType()) {
6425 QualType PointeeType = PT->getPointeeType();
6426 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6427 }
6428
6429 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6430 // be used as builtin types.
6431
6432 if (PT->isImageType())
6433 return PtrKernelParam;
6434
6435 if (PT->isBooleanType())
6436 return InvalidKernelParam;
6437
6438 if (PT->isEventT())
6439 return InvalidKernelParam;
6440
6441 if (PT->isHalfType())
6442 return InvalidKernelParam;
6443
6444 if (PT->isRecordType())
6445 return RecordKernelParam;
6446
6447 return ValidKernelParam;
6448}
6449
6450static void checkIsValidOpenCLKernelParameter(
6451 Sema &S,
6452 Declarator &D,
6453 ParmVarDecl *Param,
6454 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6455 QualType PT = Param->getType();
6456
6457 // Cache the valid types we encounter to avoid rechecking structs that are
6458 // used again
6459 if (ValidTypes.count(PT.getTypePtr()))
6460 return;
6461
6462 switch (getOpenCLKernelParameterType(PT)) {
6463 case PtrPtrKernelParam:
6464 // OpenCL v1.2 s6.9.a:
6465 // A kernel function argument cannot be declared as a
6466 // pointer to a pointer type.
6467 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6468 D.setInvalidType();
6469 return;
6470
6471 // OpenCL v1.2 s6.9.k:
6472 // Arguments to kernel functions in a program cannot be declared with the
6473 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6474 // uintptr_t or a struct and/or union that contain fields declared to be
6475 // one of these built-in scalar types.
6476
6477 case InvalidKernelParam:
6478 // OpenCL v1.2 s6.8 n:
6479 // A kernel function argument cannot be declared
6480 // of event_t type.
6481 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6482 D.setInvalidType();
6483 return;
6484
6485 case PtrKernelParam:
6486 case ValidKernelParam:
6487 ValidTypes.insert(PT.getTypePtr());
6488 return;
6489
6490 case RecordKernelParam:
6491 break;
6492 }
6493
6494 // Track nested structs we will inspect
6495 SmallVector<const Decl *, 4> VisitStack;
6496
6497 // Track where we are in the nested structs. Items will migrate from
6498 // VisitStack to HistoryStack as we do the DFS for bad field.
6499 SmallVector<const FieldDecl *, 4> HistoryStack;
6500 HistoryStack.push_back((const FieldDecl *) 0);
6501
6502 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6503 VisitStack.push_back(PD);
6504
6505 assert(VisitStack.back() && "First decl null?");
6506
6507 do {
6508 const Decl *Next = VisitStack.pop_back_val();
6509 if (!Next) {
6510 assert(!HistoryStack.empty());
6511 // Found a marker, we have gone up a level
6512 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6513 ValidTypes.insert(Hist->getType().getTypePtr());
6514
6515 continue;
6516 }
6517
6518 // Adds everything except the original parameter declaration (which is not a
6519 // field itself) to the history stack.
6520 const RecordDecl *RD;
6521 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6522 HistoryStack.push_back(Field);
6523 RD = Field->getType()->castAs<RecordType>()->getDecl();
6524 } else {
6525 RD = cast<RecordDecl>(Next);
6526 }
6527
6528 // Add a null marker so we know when we've gone back up a level
6529 VisitStack.push_back((const Decl *) 0);
6530
6531 for (RecordDecl::field_iterator I = RD->field_begin(),
6532 E = RD->field_end(); I != E; ++I) {
6533 const FieldDecl *FD = *I;
6534 QualType QT = FD->getType();
6535
6536 if (ValidTypes.count(QT.getTypePtr()))
6537 continue;
6538
6539 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6540 if (ParamType == ValidKernelParam)
6541 continue;
6542
6543 if (ParamType == RecordKernelParam) {
6544 VisitStack.push_back(FD);
6545 continue;
6546 }
6547
6548 // OpenCL v1.2 s6.9.p:
6549 // Arguments to kernel functions that are declared to be a struct or union
6550 // do not allow OpenCL objects to be passed as elements of the struct or
6551 // union.
6552 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6553 S.Diag(Param->getLocation(),
6554 diag::err_record_with_pointers_kernel_param)
6555 << PT->isUnionType()
6556 << PT;
6557 } else {
6558 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6559 }
6560
6561 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6562 << PD->getDeclName();
6563
6564 // We have an error, now let's go back up through history and show where
6565 // the offending field came from
6566 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6567 E = HistoryStack.end(); I != E; ++I) {
6568 const FieldDecl *OuterField = *I;
6569 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6570 << OuterField->getType();
6571 }
6572
6573 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6574 << QT->isPointerType()
6575 << QT;
6576 D.setInvalidType();
6577 return;
6578 }
6579 } while (!VisitStack.empty());
6580}
6581
Mike Stump11289f42009-09-09 15:08:12 +00006582NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006583Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006584 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006585 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006586 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006587 QualType R = TInfo->getType();
6588
Zhongxing Xubece5d62009-01-16 01:13:29 +00006589 assert(R.getTypePtr()->isFunctionType());
6590
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006591 // TODO: consider using NameInfo for diagnostic.
6592 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6593 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006594 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006595
Richard Smithb4a9e862013-04-12 22:46:28 +00006596 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6597 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6598 diag::err_invalid_thread)
6599 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006600
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006601 if (D.isFirstDeclarationOfMember())
6602 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006603
Douglas Gregor513e63c2010-12-10 19:28:19 +00006604 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006605 FunctionTemplateDecl *FunctionTemplate = 0;
6606 bool isExplicitSpecialization = false;
6607 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006608
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006609 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006610 bool HasExplicitTemplateArgs = false;
6611 TemplateArgumentListInfo TemplateArgs;
6612
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006613 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006614
Richard Smith541b38b2013-09-20 01:15:31 +00006615 DeclContext *OriginalDC = DC;
6616 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6617
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006618 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6619 isVirtualOkay);
6620 if (!NewFD) return 0;
6621
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006622 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6623 NewFD->setTopLevelDeclInObjCContainer();
6624
Richard Smith541b38b2013-09-20 01:15:31 +00006625 // Set the lexical context. If this is a function-scope declaration, or has a
6626 // C++ scope specifier, or is the object of a friend declaration, the lexical
6627 // context will be different from the semantic context.
6628 NewFD->setLexicalDeclContext(CurContext);
6629
6630 if (IsLocalExternDecl)
6631 NewFD->setLocalExternDecl();
6632
David Blaikiebbafb8a2012-03-11 07:00:24 +00006633 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006634 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006635 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6636 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006637 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006638 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006639 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006640 // C++ [class.friend]p5
6641 // A function can be defined in a friend declaration of a
6642 // class . . . . Such a function is implicitly inline.
6643 NewFD->setImplicitlyInline();
6644 }
6645
John McCalldb632ac2012-09-25 07:32:39 +00006646 // If this is a method defined in an __interface, and is not a constructor
6647 // or an overloaded operator, then set the pure flag (isVirtual will already
6648 // return true).
6649 if (const CXXRecordDecl *Parent =
6650 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6651 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006652 NewFD->setPure(true);
6653 }
6654
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006655 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006656 isExplicitSpecialization = false;
6657 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006658 if (D.isInvalidType())
6659 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006660
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006661 // Match up the template parameter lists with the scope specifier, then
6662 // determine whether we have a template or a template specialization.
6663 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006664 if (TemplateParameterList *TemplateParams =
6665 MatchTemplateParametersToScopeSpecifier(
6666 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6667 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6668 isExplicitSpecialization, Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006669 if (TemplateParams->size() > 0) {
6670 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006671
Abramo Bagnara60804e12011-03-18 15:16:37 +00006672 // Check that we can declare a template here.
6673 if (CheckTemplateDeclScope(S, TemplateParams))
6674 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006675
Abramo Bagnara60804e12011-03-18 15:16:37 +00006676 // A destructor cannot be a template.
6677 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6678 Diag(NewFD->getLocation(), diag::err_destructor_template);
6679 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006680 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006681
6682 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006683 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006684 // now that we know what the current instantiation is.
6685 if (DC->isDependentContext()) {
6686 ContextRAII SavedContext(*this, DC);
6687 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6688 Invalid = true;
6689 }
6690
John McCall1f0479e2010-03-24 08:27:58 +00006691
Abramo Bagnara60804e12011-03-18 15:16:37 +00006692 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6693 NewFD->getLocation(),
6694 Name, TemplateParams,
6695 NewFD);
6696 FunctionTemplate->setLexicalDeclContext(CurContext);
6697 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6698
6699 // For source fidelity, store the other template param lists.
6700 if (TemplateParamLists.size() > 1) {
6701 NewFD->setTemplateParameterListsInfo(Context,
6702 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006703 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006704 }
6705 } else {
6706 // This is a function template specialization.
6707 isFunctionTemplateSpecialization = true;
6708 // For source fidelity, store all the template param lists.
6709 NewFD->setTemplateParameterListsInfo(Context,
6710 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006711 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006712
6713 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6714 if (isFriend) {
6715 // We want to remove the "template<>", found here.
6716 SourceRange RemoveRange = TemplateParams->getSourceRange();
6717
6718 // If we remove the template<> and the name is not a
6719 // template-id, we're actually silently creating a problem:
6720 // the friend declaration will refer to an untemplated decl,
6721 // and clearly the user wants a template specialization. So
6722 // we need to insert '<>' after the name.
6723 SourceLocation InsertLoc;
6724 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6725 InsertLoc = D.getName().getSourceRange().getEnd();
6726 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6727 }
6728
6729 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6730 << Name << RemoveRange
6731 << FixItHint::CreateRemoval(RemoveRange)
6732 << FixItHint::CreateInsertion(InsertLoc, "<>");
6733 }
6734 }
6735 }
6736 else {
6737 // All template param lists were matched against the scope specifier:
6738 // this is NOT (an explicit specialization of) a template.
6739 if (TemplateParamLists.size() > 0)
6740 // For source fidelity, store all the template param lists.
6741 NewFD->setTemplateParameterListsInfo(Context,
6742 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006743 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006744 }
6745
6746 if (Invalid) {
6747 NewFD->setInvalidDecl();
6748 if (FunctionTemplate)
6749 FunctionTemplate->setInvalidDecl();
6750 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006751
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006752 // C++ [dcl.fct.spec]p5:
6753 // The virtual specifier shall only be used in declarations of
6754 // nonstatic class member functions that appear within a
6755 // member-specification of a class declaration; see 10.3.
6756 //
6757 if (isVirtual && !NewFD->isInvalidDecl()) {
6758 if (!isVirtualOkay) {
6759 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6760 diag::err_virtual_non_function);
6761 } else if (!CurContext->isRecord()) {
6762 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006763 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6764 diag::err_virtual_out_of_class)
6765 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6766 } else if (NewFD->getDescribedFunctionTemplate()) {
6767 // C++ [temp.mem]p3:
6768 // A member function template shall not be virtual.
6769 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6770 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006771 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6772 } else {
6773 // Okay: Add virtual to the method.
6774 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006775 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006776
6777 if (getLangOpts().CPlusPlus1y &&
6778 NewFD->getResultType()->isUndeducedType())
6779 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006780 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006781
Richard Smithc1564702013-11-15 02:58:23 +00006782 if (getLangOpts().CPlusPlus1y &&
6783 (NewFD->isDependentContext() ||
6784 (isFriend && CurContext->isDependentContext())) &&
Richard Smithc58f38f2013-08-14 20:16:31 +00006785 NewFD->getResultType()->isUndeducedType()) {
6786 // If the function template is referenced directly (for instance, as a
6787 // member of the current instantiation), pretend it has a dependent type.
6788 // This is not really justified by the standard, but is the only sane
6789 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006790 // FIXME: For a friend function, we have not marked the function as being
6791 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006792 const FunctionProtoType *FPT =
6793 NewFD->getType()->castAs<FunctionProtoType>();
6794 QualType Result = SubstAutoType(FPT->getResultType(),
6795 Context.DependentTy);
6796 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6797 FPT->getExtProtoInfo()));
6798 }
6799
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006800 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006801 // The inline specifier shall not appear on a block scope function
6802 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006803 if (isInline && !NewFD->isInvalidDecl()) {
6804 if (CurContext->isFunctionOrMethod()) {
6805 // 'inline' is not allowed on block scope function declaration.
6806 Diag(D.getDeclSpec().getInlineSpecLoc(),
6807 diag::err_inline_declaration_block_scope) << Name
6808 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6809 }
6810 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006811
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006812 // C++ [dcl.fct.spec]p6:
6813 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006814 // constructor or conversion function within its class definition;
6815 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006816 if (isExplicit && !NewFD->isInvalidDecl()) {
6817 if (!CurContext->isRecord()) {
6818 // 'explicit' was specified outside of the class.
6819 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6820 diag::err_explicit_out_of_class)
6821 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6822 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6823 !isa<CXXConversionDecl>(NewFD)) {
6824 // 'explicit' was specified on a function that wasn't a constructor
6825 // or conversion function.
6826 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6827 diag::err_explicit_non_ctor_or_conv_function)
6828 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6829 }
6830 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006831
Richard Smitha77a0a62011-08-15 21:04:07 +00006832 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006833 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006834 // are implicitly inline.
6835 NewFD->setImplicitlyInline();
6836
Richard Smith574f4f62013-01-14 05:37:29 +00006837 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006838 // be either constructors or to return a literal type. Therefore,
6839 // destructors cannot be declared constexpr.
6840 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006841 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006842 }
6843
Douglas Gregor26701a42011-09-09 02:06:17 +00006844 // If __module_private__ was specified, mark the function accordingly.
6845 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006846 if (isFunctionTemplateSpecialization) {
6847 SourceLocation ModulePrivateLoc
6848 = D.getDeclSpec().getModulePrivateSpecLoc();
6849 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6850 << 0
6851 << FixItHint::CreateRemoval(ModulePrivateLoc);
6852 } else {
6853 NewFD->setModulePrivate();
6854 if (FunctionTemplate)
6855 FunctionTemplate->setModulePrivate();
6856 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006857 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006858
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006859 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006860 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006861 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006862 FunctionTemplate->setAccess(AS_public);
6863 }
Richard Smith64017682013-07-17 23:53:16 +00006864 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006865 NewFD->setAccess(AS_public);
6866 }
6867
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006868 // If a function is defined as defaulted or deleted, mark it as such now.
6869 switch (D.getFunctionDefinitionKind()) {
6870 case FDK_Declaration:
6871 case FDK_Definition:
6872 break;
6873
6874 case FDK_Defaulted:
6875 NewFD->setDefaulted();
6876 break;
6877
6878 case FDK_Deleted:
6879 NewFD->setDeletedAsWritten();
6880 break;
6881 }
6882
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006883 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6884 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006885 // C++ [class.mfct]p2:
6886 // A member function may be defined (8.4) in its class definition, in
6887 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006888 NewFD->setImplicitlyInline();
6889 }
6890
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006891 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6892 !CurContext->isRecord()) {
6893 // C++ [class.static]p1:
6894 // A data or function member of a class may be declared static
6895 // in a class definition, in which case it is a static member of
6896 // the class.
6897
6898 // Complain about the 'static' specifier if it's on an out-of-line
6899 // member function definition.
6900 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6901 diag::err_static_out_of_line)
6902 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6903 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006904
6905 // C++11 [except.spec]p15:
6906 // A deallocation function with no exception-specification is treated
6907 // as if it were specified with noexcept(true).
6908 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6909 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6910 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006911 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006912 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6913 EPI.ExceptionSpecType = EST_BasicNoexcept;
6914 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00006915 FPT->getArgTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006916 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006917 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006918
6919 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006920 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00006921 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006922 isExplicitSpecialization ||
6923 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006924
Zhongxing Xubece5d62009-01-16 01:13:29 +00006925 // Handle GNU asm-label extension (encoded as an attribute).
6926 if (Expr *E = (Expr*) D.getAsmLabel()) {
6927 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006928 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006929 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6930 SE->getString()));
David Chisnall0867d9c2012-02-18 16:12:34 +00006931 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6932 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6933 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6934 if (I != ExtnameUndeclaredIdentifiers.end()) {
6935 NewFD->addAttr(I->second);
6936 ExtnameUndeclaredIdentifiers.erase(I);
6937 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006938 }
6939
Chris Lattner9af40c12009-04-25 06:12:16 +00006940 // Copy the parameter declarations from the declarator D to the function
6941 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006942 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006943 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006944 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006945
Zhongxing Xubece5d62009-01-16 01:13:29 +00006946 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6947 // function that takes no arguments, not a function that takes a
6948 // single void argument.
6949 // We let through "const void" here because Sema::GetTypeForDeclarator
6950 // already checks for that case.
6951 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6952 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006953 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00006954 // Empty arg list, don't push any params.
Eli Friedman8f5e9832012-09-20 01:40:23 +00006955 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xubece5d62009-01-16 01:13:29 +00006956 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006957 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00006958 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006959 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6960 Param->setDeclContext(NewFD);
6961 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00006962
6963 if (Param->isInvalidDecl())
6964 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006965 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006966 }
Mike Stump11289f42009-09-09 15:08:12 +00006967
John McCall9dd450b2009-09-21 23:43:11 +00006968 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00006969 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00006970 // following example, we'll need to synthesize (unnamed)
6971 // parameters for use in the declaration.
6972 //
6973 // @code
6974 // typedef void fn(int);
6975 // fn f;
6976 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00006977
Chris Lattner47c0d002009-04-25 06:03:53 +00006978 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00006979 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6980 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00006981 ParmVarDecl *Param =
6982 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00006983 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00006984 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006985 }
Chris Lattner49303b22009-04-25 18:38:18 +00006986 } else {
6987 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6988 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00006989 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00006990
Chris Lattner9af40c12009-04-25 06:12:16 +00006991 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00006992 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00006993
James Molloy6f8780b2012-02-29 10:24:19 +00006994 // Find all anonymous symbols defined during the declaration of this function
6995 // and add to NewFD. This lets us track decls such 'enum Y' in:
6996 //
6997 // void f(enum Y {AA} x) {}
6998 //
6999 // which would otherwise incorrectly end up in the translation unit scope.
7000 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7001 DeclsInPrototypeScope.clear();
7002
Richard Smithdebc59d2013-01-30 05:45:05 +00007003 if (D.getDeclSpec().isNoreturnSpecified())
7004 NewFD->addAttr(
7005 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7006 Context));
7007
Richard Smith84208dc2012-03-13 05:56:40 +00007008 // Functions returning a variably modified type violate C99 6.7.5.2p2
7009 // because all functions have linkage.
7010 if (!NewFD->isInvalidDecl() &&
7011 NewFD->getResultType()->isVariablyModifiedType()) {
7012 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7013 NewFD->setInvalidDecl();
7014 }
7015
Rafael Espindolac67f2232012-05-10 02:50:16 +00007016 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00007017 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00007018
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007019 QualType RetType = NewFD->getResultType();
7020 const CXXRecordDecl *Ret = RetType->isRecordType() ?
7021 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7022 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7023 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00007024 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramer9940a5d2013-10-16 16:21:04 +00007025 // Attach the attribute to the new decl. Don't apply the attribute if it
7026 // returns an instance of the class (e.g. assignment operators).
7027 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00007028 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
7029 Context));
7030 }
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007031 }
7032
Joey Gouly16cb99d2014-01-06 11:26:18 +00007033 if (getLangOpts().OpenCL) {
7034 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7035 // type declaration will generate a compilation error.
7036 unsigned AddressSpace = RetType.getAddressSpace();
7037 if (AddressSpace == LangAS::opencl_local ||
7038 AddressSpace == LangAS::opencl_global ||
7039 AddressSpace == LangAS::opencl_constant) {
7040 Diag(NewFD->getLocation(),
7041 diag::err_opencl_return_value_with_address_space);
7042 NewFD->setInvalidDecl();
7043 }
7044 }
7045
David Blaikiebbafb8a2012-03-11 07:00:24 +00007046 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007047 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007048 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00007049 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7050 CheckMain(NewFD, D.getDeclSpec());
7051
David Majnemerc729b0b2013-09-16 22:44:20 +00007052 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7053 CheckMSVCRTEntryPoint(NewFD);
7054
David Majnemer027f9c42013-07-06 02:13:46 +00007055 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00007056 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7057 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00007058 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007059 // Make graceful recovery from an invalid redeclaration.
7060 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007061 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007062 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7063 "previous declaration set still overloaded");
7064 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007065 // C++11 [replacement.functions]p3:
7066 // The program's definitions shall not be specified as inline.
7067 //
7068 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7069 //
7070 // Suppress the diagnostic if the function is __attribute__((used)), since
7071 // that forces an external definition to be emitted.
7072 if (D.getDeclSpec().isInlineSpecified() &&
7073 NewFD->isReplaceableGlobalAllocationFunction() &&
7074 !NewFD->hasAttr<UsedAttr>())
7075 Diag(D.getDeclSpec().getInlineSpecLoc(),
7076 diag::ext_operator_new_delete_declared_inline)
7077 << NewFD->getDeclName();
7078
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007079 // If the declarator is a template-id, translate the parser's template
7080 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007081 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7082 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7083 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7084 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007085 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007086 TemplateId->NumArgs);
7087 translateTemplateArguments(TemplateArgsPtr,
7088 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007089
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007090 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007091
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007092 if (NewFD->isInvalidDecl()) {
7093 HasExplicitTemplateArgs = false;
7094 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007095 // Function template with explicit template arguments.
7096 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7097 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7098
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007099 HasExplicitTemplateArgs = false;
7100 } else if (!isFunctionTemplateSpecialization &&
7101 !D.getDeclSpec().isFriendSpecified()) {
7102 // We have encountered something that the user meant to be a
7103 // specialization (because it has explicitly-specified template
7104 // arguments) but that was not introduced with a "template<>" (or had
7105 // too few of them).
Larisse Voufo39a1e502013-08-06 01:03:05 +00007106 // FIXME: Differentiate between attempts for explicit instantiations
7107 // (starting with "template") and the rest.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007108 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7109 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7110 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007111 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00007112 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007113 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00007114 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007115 // "friend void foo<>(int);" is an implicit specialization decl.
7116 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007117 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007118 } else if (isFriend && isFunctionTemplateSpecialization) {
7119 // This combination is only possible in a recovery case; the user
7120 // wrote something like:
7121 // template <> friend void foo(int);
7122 // which we're recovering from as if the user had written:
7123 // friend void foo<>(int);
7124 // Go ahead and fake up a template id.
7125 HasExplicitTemplateArgs = true;
7126 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7127 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007128 }
John McCallf7cfb222010-10-13 05:45:15 +00007129
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007130 // If it's a friend (and only if it's a friend), it's possible
7131 // that either the specialized function type or the specialized
7132 // template is dependent, and therefore matching will fail. In
7133 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007134 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007135 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007136 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7137 TemplateSpecializationType::anyDependentTemplateArguments(
7138 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7139 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007140 assert(HasExplicitTemplateArgs &&
7141 "friend function specialization without template args");
7142 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7143 Previous))
7144 NewFD->setInvalidDecl();
7145 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007146 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007147 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007148 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007149 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007150 diag::ext_function_specialization_in_class :
7151 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007152 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007153 } else if (CheckFunctionTemplateSpecialization(NewFD,
7154 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7155 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007156 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007157
7158 // C++ [dcl.stc]p1:
7159 // A storage-class-specifier shall not be specified in an explicit
7160 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007161 FunctionTemplateSpecializationInfo *Info =
7162 NewFD->getTemplateSpecializationInfo();
7163 if (Info && SC != SC_None) {
7164 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007165 Diag(NewFD->getLocation(),
7166 diag::err_explicit_specialization_inconsistent_storage_class)
7167 << SC
7168 << FixItHint::CreateRemoval(
7169 D.getDeclSpec().getStorageClassSpecLoc());
7170
7171 else
7172 Diag(NewFD->getLocation(),
7173 diag::ext_explicit_specialization_storage_class)
7174 << FixItHint::CreateRemoval(
7175 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007176 }
7177
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007178 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7179 if (CheckMemberSpecialization(NewFD, Previous))
7180 NewFD->setInvalidDecl();
7181 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007182
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007183 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007184 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007185 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7186 CheckMain(NewFD, D.getDeclSpec());
7187
David Majnemerc729b0b2013-09-16 22:44:20 +00007188 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7189 CheckMSVCRTEntryPoint(NewFD);
7190
Nico Weber7607fce2013-12-21 00:49:51 +00007191 if (!NewFD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007192 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7193 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007194 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007195
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007196 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007197 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7198 "previous declaration set still overloaded");
7199
7200 NamedDecl *PrincipalDecl = (FunctionTemplate
7201 ? cast<NamedDecl>(FunctionTemplate)
7202 : NewFD);
7203
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007204 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007205 AccessSpecifier Access = AS_public;
7206 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007207 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007208
7209 NewFD->setAccess(Access);
7210 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007211 }
7212
7213 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7214 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7215 PrincipalDecl->setNonMemberOperator();
7216
7217 // If we have a function template, check the template parameter
7218 // list. This will check and merge default template arguments.
7219 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007220 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007221 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007222 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00007223 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007224 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007225 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007226 ? TPC_FriendFunctionTemplateDefinition
7227 : TPC_FriendFunctionTemplate)
7228 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007229 DC && DC->isRecord() &&
7230 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007231 ? TPC_ClassTemplateMember
7232 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007233 }
7234
7235 if (NewFD->isInvalidDecl()) {
7236 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007237 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007238 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007239 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007240 // Fake up an access specifier if it's supposed to be a class member.
7241 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7242 NewFD->setAccess(AS_public);
7243
7244 // Qualified decls generally require a previous declaration.
7245 if (D.getCXXScopeSpec().isSet()) {
7246 // ...with the major exception of templated-scope or
7247 // dependent-scope friend declarations.
7248
7249 // TODO: we currently also suppress this check in dependent
7250 // contexts because (1) the parameter depth will be off when
7251 // matching friend templates and (2) we might actually be
7252 // selecting a friend based on a dependent factor. But there
7253 // are situations where these conditions don't apply and we
7254 // can actually do this check immediately.
7255 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007256 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007257 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7258 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007259 // ignore these
7260 } else {
7261 // The user tried to provide an out-of-line definition for a
7262 // function that is a member of a class or namespace, but there
7263 // was no such member function declared (C++ [class.mfct]p2,
7264 // C++ [namespace.memdef]p2). For example:
7265 //
7266 // class X {
7267 // void f() const;
7268 // };
7269 //
7270 // void X::f() { } // ill-formed
7271 //
7272 // Complain about this problem, and attempt to suggest close
7273 // matches (e.g., those that differ only in cv-qualifiers and
7274 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007275
Richard Smith114394f2013-08-09 04:35:01 +00007276 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7277 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007278 AddToScope = ExtraArgs.AddToScope;
7279 return Result;
7280 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007281 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007282
7283 // Unqualified local friend declarations are required to resolve
7284 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007285 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007286 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7287 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007288 AddToScope = ExtraArgs.AddToScope;
7289 return Result;
7290 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007291 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007292
Richard Smitha2302242013-12-05 07:51:02 +00007293 } else if (!D.isFunctionDefinition() &&
7294 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007295 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007296 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007297 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007298 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007299 // Note that this is not the case for explicit specializations of
7300 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007301 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7302 // extension for compatibility with old SWIG code which likes to
7303 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007304 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7305 << D.getCXXScopeSpec().getRange();
7306 }
7307 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007308
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007309 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007310 checkAttributesAfterMerging(*this, *NewFD);
7311
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007312 AddKnownFunctionAttributes(NewFD);
7313
Douglas Gregor72609052010-08-06 13:50:58 +00007314 if (NewFD->hasAttr<OverloadableAttr>() &&
7315 !NewFD->getType()->getAs<FunctionProtoType>()) {
7316 Diag(NewFD->getLocation(),
7317 diag::err_attribute_overloadable_no_prototype)
7318 << NewFD;
7319
7320 // Turn this into a variadic function with no parameters.
7321 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007322 FunctionProtoType::ExtProtoInfo EPI(
7323 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007324 EPI.Variadic = true;
7325 EPI.ExtInfo = FT->getExtInfo();
7326
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007327 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007328 NewFD->setType(R);
7329 }
7330
Eli Friedman570024a2010-08-05 06:57:20 +00007331 // If there's a #pragma GCC visibility in scope, and this isn't a class
7332 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007333 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007334 AddPushedVisibilityAttribute(NewFD);
7335
John McCall32f5fe12011-09-30 05:12:12 +00007336 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7337 // marking the function.
7338 AddCFAuditedAttribute(NewFD);
7339
Richard Smithac974a32013-06-30 09:48:50 +00007340 // If this is the first declaration of an extern C variable, update
7341 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007342 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007343 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007344 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007345
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007346 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007347 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007348
David Blaikiebbafb8a2012-03-11 07:00:24 +00007349 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007350 if (FunctionTemplate) {
7351 if (NewFD->isInvalidDecl())
7352 FunctionTemplate->setInvalidDecl();
7353 return FunctionTemplate;
7354 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007355 }
Mike Stump11289f42009-09-09 15:08:12 +00007356
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007357 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007358 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7359 if ((getLangOpts().OpenCLVersion >= 120)
7360 && (SC == SC_Static)) {
7361 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7362 D.setInvalidType();
7363 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007364
7365 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7366 if (!NewFD->getResultType()->isVoidType()) {
7367 Diag(D.getIdentifierLoc(),
7368 diag::err_expected_kernel_void_return_type);
7369 D.setInvalidType();
7370 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007371
7372 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007373 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7374 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly39989da2013-01-29 10:54:06 +00007375 ParmVarDecl *Param = *PI;
Matt Arsenaultefb38192013-07-23 01:23:36 +00007376 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007377 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007378 }
7379
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007380 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007381
David Blaikiebbafb8a2012-03-11 07:00:24 +00007382 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007383 if (IdentifierInfo *II = NewFD->getIdentifier())
7384 if (!NewFD->isInvalidDecl() &&
7385 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7386 if (II->isStr("cudaConfigureCall")) {
7387 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7388 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7389
7390 Context.setcudaConfigureCallDecl(NewFD);
7391 }
7392 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007393
7394 // Here we have an function template explicit specialization at class scope.
7395 // The actually specialization will be postponed to template instatiation
7396 // time via the ClassScopeFunctionSpecializationDecl node.
7397 if (isDependentClassScopeExplicitSpecialization) {
7398 ClassScopeFunctionSpecializationDecl *NewSpec =
7399 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007400 Context, CurContext, SourceLocation(),
7401 cast<CXXMethodDecl>(NewFD),
7402 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007403 CurContext->addDecl(NewSpec);
7404 AddToScope = false;
7405 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007406
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007407 return NewFD;
7408}
7409
7410/// \brief Perform semantic checking of a new function declaration.
7411///
7412/// Performs semantic analysis of the new function declaration
7413/// NewFD. This routine performs all semantic checking that does not
7414/// require the actual declarator involved in the declaration, and is
7415/// used both for the declaration of functions as they are parsed
7416/// (called via ActOnDeclarator) and for the declaration of functions
7417/// that have been instantiated via C++ template instantiation (called
7418/// via InstantiateDecl).
7419///
James Dennettffad8b72012-06-22 08:10:18 +00007420/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007421/// an explicit specialization of the previous declaration.
7422///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007423/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007424///
James Dennettffad8b72012-06-22 08:10:18 +00007425/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007426bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007427 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007428 bool IsExplicitSpecialization) {
David Blaikied937bf12011-09-08 06:33:04 +00007429 assert(!NewFD->getResultType()->isVariablyModifiedType()
7430 && "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007431
Richard Smith1c34fb72013-08-13 18:18:50 +00007432 // Determine whether the type of this function should be merged with
7433 // a previous visible declaration. This never happens for functions in C++,
7434 // and always happens in C if the previous declaration was visible.
7435 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7436 !Previous.isShadowed();
7437
Douglas Gregor3552dab2013-01-09 00:47:56 +00007438 // Filter out any non-conflicting previous declarations.
7439 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7440
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007441 bool Redeclaration = false;
Richard Smith574f4f62013-01-14 05:37:29 +00007442 NamedDecl *OldDecl = 0;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007443
Douglas Gregore62c0a42009-02-24 01:23:02 +00007444 // Merge or overload the declaration with an existing declaration of
7445 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007446 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007447 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007448 // a declaration that requires merging. If it's an overload,
7449 // there's no more work to do here; we'll just add the new
7450 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007451 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007452 NamedDecl *Candidate = Previous.getFoundDecl();
7453 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7454 Redeclaration = true;
7455 OldDecl = Candidate;
7456 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007457 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007458 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7459 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007460 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007461 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007462 break;
7463
7464 case Ovl_NonFunction:
7465 Redeclaration = true;
7466 break;
7467
7468 case Ovl_Overload:
7469 Redeclaration = false;
7470 break;
John McCall1f82f242009-11-18 22:49:29 +00007471 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007472
David Blaikiebbafb8a2012-03-11 07:00:24 +00007473 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007474 // If a function name is overloadable in C, then every function
7475 // with that name must be marked "overloadable".
7476 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7477 << Redeclaration << NewFD;
7478 NamedDecl *OverloadedDecl = 0;
7479 if (Redeclaration)
7480 OverloadedDecl = OldDecl;
7481 else if (!Previous.empty())
7482 OverloadedDecl = Previous.getRepresentativeDecl();
7483 if (OverloadedDecl)
7484 Diag(OverloadedDecl->getLocation(),
7485 diag::note_attribute_overloadable_prev_overload);
7486 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7487 Context));
7488 }
John McCall1f82f242009-11-18 22:49:29 +00007489 }
Richard Smith574f4f62013-01-14 05:37:29 +00007490 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007491
Richard Smithac974a32013-06-30 09:48:50 +00007492 // Check for a previous extern "C" declaration with this name.
7493 if (!Redeclaration &&
7494 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7495 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7496 if (!Previous.empty()) {
7497 // This is an extern "C" declaration with the same name as a previous
7498 // declaration, and thus redeclares that entity...
7499 Redeclaration = true;
7500 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007501 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007502
7503 // ... except in the presence of __attribute__((overloadable)).
7504 if (OldDecl->hasAttr<OverloadableAttr>()) {
7505 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7506 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7507 << Redeclaration << NewFD;
7508 Diag(Previous.getFoundDecl()->getLocation(),
7509 diag::note_attribute_overloadable_prev_overload);
7510 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7511 Context));
7512 }
7513 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7514 Redeclaration = false;
7515 OldDecl = 0;
7516 }
7517 }
7518 }
7519 }
7520
Richard Smith574f4f62013-01-14 05:37:29 +00007521 // C++11 [dcl.constexpr]p8:
7522 // A constexpr specifier for a non-static member function that is not
7523 // a constructor declares that member function to be const.
7524 //
7525 // This needs to be delayed until we know whether this is an out-of-line
7526 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007527 //
7528 // This rule is not present in C++1y, so we produce a backwards
7529 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007530 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007531 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7532 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007533 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7534 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7535 if (FunctionTemplateDecl *OldTD =
7536 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7537 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7538 if (!OldMD || !OldMD->isStatic()) {
7539 const FunctionProtoType *FPT =
7540 MD->getType()->castAs<FunctionProtoType>();
7541 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7542 EPI.TypeQuals |= Qualifiers::Const;
7543 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00007544 FPT->getArgTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007545
7546 // Warn that we did this, if we're not performing template instantiation.
7547 // In that case, we'll have warned already when the template was defined.
7548 if (ActiveTemplateInstantiations.empty()) {
7549 SourceLocation AddConstLoc;
7550 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7551 .IgnoreParens().getAs<FunctionTypeLoc>())
7552 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7553
7554 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7555 << FixItHint::CreateInsertion(AddConstLoc, " const");
7556 }
Richard Smith574f4f62013-01-14 05:37:29 +00007557 }
7558 }
7559
7560 if (Redeclaration) {
7561 // NewFD and OldDecl represent declarations that need to be
7562 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007563 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007564 NewFD->setInvalidDecl();
7565 return Redeclaration;
7566 }
7567
7568 Previous.clear();
7569 Previous.addDecl(OldDecl);
7570
7571 if (FunctionTemplateDecl *OldTemplateDecl
7572 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7573 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7574 FunctionTemplateDecl *NewTemplateDecl
7575 = NewFD->getDescribedFunctionTemplate();
7576 assert(NewTemplateDecl && "Template/non-template mismatch");
7577 if (CXXMethodDecl *Method
7578 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7579 Method->setAccess(OldTemplateDecl->getAccess());
7580 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007581 }
Richard Smith574f4f62013-01-14 05:37:29 +00007582
7583 // If this is an explicit specialization of a member that is a function
7584 // template, mark it as a member specialization.
7585 if (IsExplicitSpecialization &&
7586 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7587 NewTemplateDecl->setMemberSpecialization();
7588 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007589 }
Richard Smith574f4f62013-01-14 05:37:29 +00007590
7591 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007592 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007593 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007594
7595 if (isa<CXXMethodDecl>(NewFD)) {
7596 // A valid redeclaration of a C++ method must be out-of-line,
7597 // but (unfortunately) it's not necessarily a definition
7598 // because of templates, which means that the previous
7599 // declaration is not necessarily from the class definition.
7600
7601 // For just setting the access, that doesn't matter.
7602 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7603 NewFD->setAccess(oldMethod->getAccess());
7604
7605 // Update the key-function state if necessary for this ABI.
7606 if (NewFD->isInlined() &&
7607 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7608 // setNonKeyFunction needs to work with the original
7609 // declaration from the class definition, and isVirtual() is
7610 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007611 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007612 if (oldMethod->isVirtual()) {
7613 Context.setNonKeyFunction(oldMethod);
7614 }
7615 }
7616 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007617 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007618 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007619
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007620 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007621 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007622 // C++-specific checks.
7623 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7624 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007625 } else if (CXXDestructorDecl *Destructor =
7626 dyn_cast<CXXDestructorDecl>(NewFD)) {
7627 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007628 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007629
Douglas Gregor7454c562010-07-02 20:37:36 +00007630 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007631 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007632 if (!ClassType->isDependentType()) {
7633 DeclarationName Name
7634 = Context.DeclarationNames.getCXXDestructorName(
7635 Context.getCanonicalType(ClassType));
7636 if (NewFD->getDeclName() != Name) {
7637 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007638 NewFD->setInvalidDecl();
7639 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007640 }
7641 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007642 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007643 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007644 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007645 }
7646
7647 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007648 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7649 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007650 !Method->getDescribedFunctionTemplate() &&
7651 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007652 if (AddOverriddenMethods(Method->getParent(), Method)) {
7653 // If the function was marked as "static", we have a problem.
7654 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007655 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007656 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007657 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007658 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007659
7660 if (Method->isStatic())
7661 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007662 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007663
7664 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7665 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007666 CheckOverloadedOperatorDeclaration(NewFD)) {
7667 NewFD->setInvalidDecl();
7668 return Redeclaration;
7669 }
Alexis Huntc88db062010-01-13 09:01:02 +00007670
7671 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7672 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007673 CheckLiteralOperatorDeclaration(NewFD)) {
7674 NewFD->setInvalidDecl();
7675 return Redeclaration;
7676 }
Alexis Huntc88db062010-01-13 09:01:02 +00007677
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007678 // In C++, check default arguments now that we have merged decls. Unless
7679 // the lexical context is the class, because in this case this is done
7680 // during delayed parsing anyway.
7681 if (!CurContext->isRecord())
7682 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007683
Douglas Gregor9246b682010-12-21 19:47:46 +00007684 // If this function declares a builtin function, check the type of this
7685 // declaration against the expected type for the builtin.
7686 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7687 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007688 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007689 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7690 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7691 // The type of this function differs from the type of the builtin,
7692 // so forget about the builtin entirely.
7693 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7694 }
7695 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007696
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007697 // If this function is declared as being extern "C", then check to see if
7698 // the function returns a UDT (class, struct, or union type) that is not C
7699 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007700 // But, issue any diagnostic on the first declaration only.
7701 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007702 QualType R = NewFD->getResultType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007703 if (R->isIncompleteType() && !R->isVoidType())
7704 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7705 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007706 else if (!R.isPODType(Context) && !R->isVoidType() &&
7707 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007708 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007709 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007710 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007711 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007712}
7713
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007714static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7715 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7716 if (!TSI)
7717 return SourceRange();
7718
7719 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007720 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007721 if (!FunctionTL)
7722 return SourceRange();
7723
David Blaikie6adc78e2013-02-18 22:06:02 +00007724 TypeLoc ResultTL = FunctionTL.getResultLoc();
7725 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007726 return ResultTL.getSourceRange();
7727
7728 return SourceRange();
7729}
7730
David Blaikied937bf12011-09-08 06:33:04 +00007731void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smith3f333f22012-02-04 06:10:17 +00007732 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7733 // static or constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007734 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7735 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007736 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007737 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007738 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007739 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007740 ? diag::err_static_main : diag::warn_static_main)
7741 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7742 if (FD->isInlineSpecified())
7743 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7744 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007745 if (DS.isNoreturnSpecified()) {
7746 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7747 SourceRange NoreturnRange(NoreturnLoc,
7748 PP.getLocForEndOfToken(NoreturnLoc));
7749 Diag(NoreturnLoc, diag::ext_noreturn_main);
7750 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7751 << FixItHint::CreateRemoval(NoreturnRange);
7752 }
Richard Smith3f333f22012-02-04 06:10:17 +00007753 if (FD->isConstexpr()) {
7754 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7755 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7756 FD->setConstexpr(false);
7757 }
John McCall02dee0a2009-07-25 04:36:53 +00007758
Joey Goulya7310a82013-11-05 12:30:39 +00007759 if (getLangOpts().OpenCL) {
7760 Diag(FD->getLocation(), diag::err_opencl_no_main)
7761 << FD->hasAttr<OpenCLKernelAttr>();
7762 FD->setInvalidDecl();
7763 return;
7764 }
7765
John McCall02dee0a2009-07-25 04:36:53 +00007766 QualType T = FD->getType();
7767 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007768 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007769
John McCall5ed3caf2012-02-14 19:50:52 +00007770 // All the standards say that main() should should return 'int'.
7771 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7772 // In C and C++, main magically returns 0 if you fall off the end;
7773 // set the flag which tells us that.
7774 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7775 FD->setHasImplicitReturnZero(true);
7776
7777 // In C with GNU extensions we allow main() to have non-integer return
7778 // type, but we should warn about the extension, and we disable the
7779 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007780 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007781 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7782
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007783 SourceRange ResultRange = getResultSourceRange(FD);
7784 if (ResultRange.isValid())
7785 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7786 << FixItHint::CreateReplacement(ResultRange, "int");
7787
John McCall5ed3caf2012-02-14 19:50:52 +00007788 // Otherwise, this is just a flat-out error.
7789 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007790 SourceRange ResultRange = getResultSourceRange(FD);
7791 if (ResultRange.isValid())
7792 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7793 << FixItHint::CreateReplacement(ResultRange, "int");
7794 else
7795 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7796
John McCall02dee0a2009-07-25 04:36:53 +00007797 FD->setInvalidDecl(true);
7798 }
7799
7800 // Treat protoless main() as nullary.
7801 if (isa<FunctionNoProtoType>(FT)) return;
7802
7803 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7804 unsigned nparams = FTP->getNumArgs();
7805 assert(FD->getNumParams() == nparams);
7806
John McCall0e21fcc2009-12-24 09:58:38 +00007807 bool HasExtraParameters = (nparams > 3);
7808
7809 // Darwin passes an undocumented fourth argument of type char**. If
7810 // other platforms start sprouting these, the logic below will start
7811 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007812 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007813 HasExtraParameters = false;
7814
7815 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007816 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7817 FD->setInvalidDecl(true);
7818 nparams = 3;
7819 }
7820
7821 // FIXME: a lot of the following diagnostics would be improved
7822 // if we had some location information about types.
7823
7824 QualType CharPP =
7825 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007826 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007827
7828 for (unsigned i = 0; i < nparams; ++i) {
7829 QualType AT = FTP->getArgType(i);
7830
7831 bool mismatch = true;
7832
7833 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7834 mismatch = false;
7835 else if (Expected[i] == CharPP) {
7836 // As an extension, the following forms are okay:
7837 // char const **
7838 // char const * const *
7839 // char * const *
7840
John McCall8ccfcb52009-09-24 19:53:00 +00007841 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007842 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007843 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7844 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007845 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7846 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007847 qs.removeConst();
7848 mismatch = !qs.empty();
7849 }
7850 }
7851
7852 if (mismatch) {
7853 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7854 // TODO: suggest replacing given type with expected type
7855 FD->setInvalidDecl(true);
7856 }
7857 }
7858
7859 if (nparams == 1 && !FD->isInvalidDecl()) {
7860 Diag(FD->getLocation(), diag::warn_main_one_arg);
7861 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007862
7863 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007864 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007865 FD->setInvalidDecl();
7866 }
7867}
7868
7869void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7870 QualType T = FD->getType();
7871 assert(T->isFunctionType() && "function decl is not of function type");
7872 const FunctionType *FT = T->castAs<FunctionType>();
7873
7874 // Set an implicit return of 'zero' if the function can return some integral,
7875 // enumeration, pointer or nullptr type.
7876 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7877 FT->getResultType()->isAnyPointerType() ||
7878 FT->getResultType()->isNullPtrType())
7879 // DllMain is exempt because a return value of zero means it failed.
7880 if (FD->getName() != "DllMain")
7881 FD->setHasImplicitReturnZero(true);
7882
7883 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007884 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007885 FD->setInvalidDecl();
7886 }
John McCalld9baf6a2009-07-24 03:03:21 +00007887}
7888
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007889bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007890 // FIXME: Need strict checking. In C89, we need to check for
7891 // any assignment, increment, decrement, function-calls, or
7892 // commas outside of a sizeof. In C99, it's the same list,
7893 // except that the aforementioned are allowed in unevaluated
7894 // expressions. Everything else falls under the
7895 // "may accept other forms of constant expressions" exception.
7896 // (We never end up here for C++, so the constant expression
7897 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007898 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007899 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007900 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7901 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007902 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007903}
7904
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007905namespace {
7906 // Visits an initialization expression to see if OrigDecl is evaluated in
7907 // its own initialization and throws a warning if it does.
7908 class SelfReferenceChecker
7909 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7910 Sema &S;
7911 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007912 bool isRecordType;
7913 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007914 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007915
7916 public:
7917 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7918
7919 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007920 S(S), OrigDecl(OrigDecl) {
7921 isPODType = false;
7922 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007923 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007924 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7925 isPODType = VD->getType().isPODType(S.Context);
7926 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007927 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007928 }
7929 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007930
Richard Trieu64c51ab2012-05-09 00:21:34 +00007931 // For most expressions, the cast is directly above the DeclRefExpr.
7932 // For conditional operators, the cast can be outside the conditional
7933 // operator if both expressions are DeclRefExpr's.
7934 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007935 if (isReferenceType)
7936 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007937 E = E->IgnoreParenImpCasts();
7938 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7939 HandleDeclRefExpr(DRE);
7940 return;
7941 }
7942
7943 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7944 HandleValue(CO->getTrueExpr());
7945 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007946 return;
7947 }
7948
7949 if (isa<MemberExpr>(E)) {
7950 Expr *Base = E->IgnoreParenImpCasts();
7951 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7952 // Check for static member variables and don't warn on them.
7953 if (!isa<FieldDecl>(ME->getMemberDecl()))
7954 return;
7955 Base = ME->getBase()->IgnoreParenImpCasts();
7956 }
7957 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7958 HandleDeclRefExpr(DRE);
7959 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007960 }
7961 }
7962
Richard Trieu32673472012-10-01 17:39:51 +00007963 // Reference types are handled here since all uses of references are
7964 // bad, not just r-value uses.
7965 void VisitDeclRefExpr(DeclRefExpr *E) {
7966 if (isReferenceType)
7967 HandleDeclRefExpr(E);
7968 }
7969
Richard Trieu64c51ab2012-05-09 00:21:34 +00007970 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00007971 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00007972 (isRecordType && E->getCastKind() == CK_NoOp))
7973 HandleValue(E->getSubExpr());
7974
7975 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007976 }
7977
Richard Trieua04ad1a2011-09-01 21:44:13 +00007978 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00007979 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00007980 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007981
Richard Trieu742c6ed2012-10-03 00:41:36 +00007982 // Warn when a non-static method call is followed by non-static member
7983 // field accesses, which is followed by a DeclRefExpr.
7984 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7985 bool Warn = (MD && !MD->isStatic());
7986 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7987 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7988 if (!isa<FieldDecl>(ME->getMemberDecl()))
7989 Warn = false;
7990 Base = ME->getBase()->IgnoreParenImpCasts();
7991 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007992
Richard Trieu742c6ed2012-10-03 00:41:36 +00007993 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7994 if (Warn)
7995 HandleDeclRefExpr(DRE);
7996 return;
7997 }
7998
7999 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8000 // Visit that expression.
8001 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008002 }
8003
Richard Trieu8fbd91d2013-03-26 03:41:40 +00008004 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8005 if (E->getNumArgs() > 0)
8006 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
8007 HandleDeclRefExpr(DRE);
8008
8009 Inherited::VisitCXXOperatorCallExpr(E);
8010 }
8011
Richard Trieua04ad1a2011-09-01 21:44:13 +00008012 void VisitUnaryOperator(UnaryOperator *E) {
8013 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00008014 if (E->getOpcode() == UO_AddrOf && isRecordType &&
8015 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8016 if (!isPODType)
8017 HandleValue(E->getSubExpr());
8018 return;
8019 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008020 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00008021 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00008022
8023 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8024
Richard Trieua04ad1a2011-09-01 21:44:13 +00008025 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00008026 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008027 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00008028 unsigned diag;
8029 if (isReferenceType) {
8030 diag = diag::warn_uninit_self_reference_in_reference_init;
8031 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8032 diag = diag::warn_static_self_reference_in_init;
8033 } else {
8034 diag = diag::warn_uninit_self_reference_in_init;
8035 }
8036
Richard Trieua04ad1a2011-09-01 21:44:13 +00008037 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00008038 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00008039 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008040 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00008041 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008042 }
8043 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008044
Richard Trieu32673472012-10-01 17:39:51 +00008045 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8046 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8047 bool DirectInit) {
8048 // Parameters arguments are occassionially constructed with itself,
8049 // for instance, in recursive functions. Skip them.
8050 if (isa<ParmVarDecl>(OrigDecl))
8051 return;
8052
8053 E = E->IgnoreParens();
8054
8055 // Skip checking T a = a where T is not a record or reference type.
8056 // Doing so is a way to silence uninitialized warnings.
8057 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8058 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8059 if (ICE->getCastKind() == CK_LValueToRValue)
8060 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8061 if (DRE->getDecl() == OrigDecl)
8062 return;
8063
8064 SelfReferenceChecker(S, OrigDecl).Visit(E);
8065 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008066}
8067
Douglas Gregor5fb53972009-01-14 15:45:31 +00008068/// AddInitializerToDecl - Adds the initializer Init to the
8069/// declaration dcl. If DirectInit is true, this is C++ direct
8070/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008071void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8072 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008073 // If there is no declaration, there was an error parsing it. Just ignore
8074 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008075 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008076 return;
Mike Stump11289f42009-09-09 15:08:12 +00008077
Douglas Gregor0c880302009-03-11 23:00:04 +00008078 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8079 // With declarators parsed the way they are, the parser cannot
8080 // distinguish between a normal initializer and a pure-specifier.
8081 // Thus this grotesque test.
8082 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008083 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008084 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8085 CheckPureMethod(Method, Init->getSourceRange());
8086 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008087 Diag(Method->getLocation(), diag::err_member_function_initialization)
8088 << Method->getDeclName() << Init->getSourceRange();
8089 Method->setInvalidDecl();
8090 }
8091 return;
8092 }
8093
Steve Naroff437b4d82007-09-12 20:13:48 +00008094 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8095 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008096 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8097 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008098 RealDecl->setInvalidDecl();
8099 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008100 }
Sebastian Redla9351792012-02-11 23:51:47 +00008101 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8102
Richard Smith0cc85782011-12-15 19:20:59 +00008103 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008104 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008105 Expr *DeduceInit = Init;
8106 // Initializer could be a C++ direct-initializer. Deduction only works if it
8107 // contains exactly one expression.
8108 if (CXXDirectInit) {
8109 if (CXXDirectInit->getNumExprs() == 0) {
8110 // It isn't possible to write this directly, but it is possible to
8111 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008112 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008113 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8114 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008115 << VDecl->getDeclName() << VDecl->getType()
8116 << VDecl->getSourceRange();
8117 RealDecl->setInvalidDecl();
8118 return;
8119 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008120 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008121 VDecl->isInitCapture()
8122 ? diag::err_init_capture_multiple_expressions
8123 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008124 << VDecl->getDeclName() << VDecl->getType()
8125 << VDecl->getSourceRange();
8126 RealDecl->setInvalidDecl();
8127 return;
8128 } else {
8129 DeduceInit = CXXDirectInit->getExpr(0);
8130 }
8131 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008132
8133 // Expressions default to 'id' when we're in a debugger.
8134 bool DefaultedToAuto = false;
8135 if (getLangOpts().DebuggerCastResultToId &&
8136 Init->getType() == Context.UnknownAnyTy) {
8137 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8138 if (Result.isInvalid()) {
8139 VDecl->setInvalidDecl();
8140 return;
8141 }
8142 Init = Result.take();
8143 DefaultedToAuto = true;
8144 }
Richard Smith061f1e22013-04-30 21:23:01 +00008145
8146 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008147 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008148 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008149 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008150 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008151 RealDecl->setInvalidDecl();
8152 return;
8153 }
Richard Smith061f1e22013-04-30 21:23:01 +00008154 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008155 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008156
John McCall31168b02011-06-15 23:02:42 +00008157 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008158 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008159 VDecl->setInvalidDecl();
8160
Jordan Rosed8d56692012-06-08 22:46:07 +00008161 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8162 // 'id' instead of a specific object type prevents most of our usual checks.
8163 // We only want to warn outside of template instantiations, though:
8164 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008165 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008166 DeducedType->isObjCIdType()) {
8167 SourceLocation Loc =
8168 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008169 Diag(Loc, diag::warn_auto_var_is_id)
8170 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8171 }
8172
Richard Smith30482bc2011-02-20 03:19:35 +00008173 // If this is a redeclaration, check that the type we just deduced matches
8174 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008175 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8176 // We never need to merge the type, because we cannot form an incomplete
8177 // array of auto, nor deduce such a type.
8178 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8179 }
Richard Smith27d807c2013-04-30 13:56:41 +00008180
8181 // Check the deduced type is valid for a variable declaration.
8182 CheckVariableDeclarationType(VDecl);
8183 if (VDecl->isInvalidDecl())
8184 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008185 }
Richard Smith0cc85782011-12-15 19:20:59 +00008186
8187 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8188 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8189 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8190 VDecl->setInvalidDecl();
8191 return;
8192 }
8193
Sebastian Redla9351792012-02-11 23:51:47 +00008194 if (!VDecl->getType()->isDependentType()) {
8195 // A definition must end up with a complete type, which means it must be
8196 // complete with the restriction that an array type might be completed by
8197 // the initializer; note that later code assumes this restriction.
8198 QualType BaseDeclType = VDecl->getType();
8199 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8200 BaseDeclType = Array->getElementType();
8201 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8202 diag::err_typecheck_decl_incomplete_type)) {
8203 RealDecl->setInvalidDecl();
8204 return;
8205 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008206
Sebastian Redla9351792012-02-11 23:51:47 +00008207 // The variable can not have an abstract class type.
8208 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8209 diag::err_abstract_type_in_decl,
8210 AbstractVariableType))
8211 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008212 }
8213
Sebastian Redl5ca79842010-02-01 20:16:42 +00008214 const VarDecl *Def;
8215 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008216 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008217 << VDecl->getDeclName();
8218 Diag(Def->getLocation(), diag::note_previous_definition);
8219 VDecl->setInvalidDecl();
8220 return;
8221 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008222
Douglas Gregorf0f83692010-08-24 05:27:49 +00008223 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008224 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008225 // C++ [class.static.data]p4
8226 // If a static data member is of const integral or const
8227 // enumeration type, its declaration in the class definition can
8228 // specify a constant-initializer which shall be an integral
8229 // constant expression (5.19). In that case, the member can appear
8230 // in integral constant expressions. The member shall still be
8231 // defined in a namespace scope if it is used in the program and the
8232 // namespace scope definition shall not contain an initializer.
8233 //
8234 // We already performed a redefinition check above, but for static
8235 // data members we also need to check whether there was an in-class
8236 // declaration with an initializer.
8237 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008238 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8239 << VDecl->getDeclName();
8240 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008241 return;
8242 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008243
Douglas Gregor71f39c92010-12-16 01:31:22 +00008244 if (VDecl->hasLocalStorage())
8245 getCurFunction()->setHasBranchProtectedScope();
8246
8247 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8248 VDecl->setInvalidDecl();
8249 return;
8250 }
8251 }
John McCalld4e1b762010-08-01 01:24:59 +00008252
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008253 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8254 // a kernel function cannot be initialized."
8255 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8256 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8257 VDecl->setInvalidDecl();
8258 return;
8259 }
8260
Steve Naroff61091402007-09-12 14:07:44 +00008261 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008262 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008263 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008264
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008265 // Expressions default to 'id' when we're in a debugger
8266 // and we are assigning it to a variable of Objective-C pointer type.
8267 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8268 Init->getType() == Context.UnknownAnyTy) {
8269 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8270 if (Result.isInvalid()) {
8271 VDecl->setInvalidDecl();
8272 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008273 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008274 Init = Result.take();
8275 }
Richard Smith0cc85782011-12-15 19:20:59 +00008276
8277 // Perform the initialization.
8278 if (!VDecl->isInvalidDecl()) {
8279 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8280 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008281 = DirectInit ?
8282 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8283 Init->getLocStart(),
8284 Init->getLocEnd())
8285 : InitializationKind::CreateDirectList(
8286 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008287 : InitializationKind::CreateCopy(VDecl->getLocation(),
8288 Init->getLocStart());
8289
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008290 MultiExprArg Args = Init;
8291 if (CXXDirectInit)
8292 Args = MultiExprArg(CXXDirectInit->getExprs(),
8293 CXXDirectInit->getNumExprs());
8294
8295 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8296 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008297 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008298 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008299 return;
Steve Naroff61091402007-09-12 14:07:44 +00008300 }
Richard Smith0cc85782011-12-15 19:20:59 +00008301
8302 Init = Result.takeAs<Expr>();
8303 }
8304
Richard Trieu32673472012-10-01 17:39:51 +00008305 // Check for self-references within variable initializers.
8306 // Variables declared within a function/method body (except for references)
8307 // are handled by a dataflow analysis.
8308 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8309 VDecl->getType()->isReferenceType()) {
8310 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8311 }
8312
Richard Smith0cc85782011-12-15 19:20:59 +00008313 // If the type changed, it means we had an incomplete type that was
8314 // completed by the initializer. For example:
8315 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008316 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008317 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008318 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008319
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008320 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008321 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8322
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008323 if (VDecl->hasAttr<BlocksAttr>())
8324 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008325
8326 // It is safe to assign a weak reference into a strong variable.
8327 // Although this code can still have problems:
8328 // id x = self.weakProp;
8329 // id y = self.weakProp;
8330 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8331 // paths through the function. This should be revisited if
8332 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008333 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008334 DiagnosticsEngine::Level Level =
8335 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8336 Init->getLocStart());
8337 if (Level != DiagnosticsEngine::Ignored)
8338 getCurFunction()->markSafeWeakUse(Init);
8339 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008340 }
8341
Richard Smith945f8d32013-01-14 22:39:08 +00008342 // The initialization is usually a full-expression.
8343 //
8344 // FIXME: If this is a braced initialization of an aggregate, it is not
8345 // an expression, and each individual field initializer is a separate
8346 // full-expression. For instance, in:
8347 //
8348 // struct Temp { ~Temp(); };
8349 // struct S { S(Temp); };
8350 // struct T { S a, b; } t = { Temp(), Temp() }
8351 //
8352 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008353 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8354 false,
8355 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008356 if (Result.isInvalid()) {
8357 VDecl->setInvalidDecl();
8358 return;
8359 }
8360 Init = Result.take();
8361
Richard Smith0cc85782011-12-15 19:20:59 +00008362 // Attach the initializer to the decl.
8363 VDecl->setInit(Init);
8364
8365 if (VDecl->isLocalVarDecl()) {
8366 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8367 // static storage duration shall be constant expressions or string literals.
8368 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008369 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8370 if (VDecl->getStorageClass() == SC_Static)
8371 CheckForConstantInitializer(Init, DclT);
8372 // C89 is stricter than C99 for non-static aggregate types.
8373 // C89 6.5.7p3: All the expressions [...] in an initializer list
8374 // for an object that has aggregate or union type shall be
8375 // constant expressions.
8376 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008377 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008378 !Init->isConstantInitializer(Context, false))
8379 Diag(Init->getExprLoc(),
8380 diag::ext_aggregate_init_not_constant)
8381 << Init->getSourceRange();
8382 }
Mike Stump11289f42009-09-09 15:08:12 +00008383 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008384 VDecl->getLexicalDeclContext()->isRecord()) {
8385 // This is an in-class initialization for a static data member, e.g.,
8386 //
8387 // struct S {
8388 // static const int value = 17;
8389 // };
8390
Douglas Gregor0c880302009-03-11 23:00:04 +00008391 // C++ [class.mem]p4:
8392 // A member-declarator can contain a constant-initializer only
8393 // if it declares a static member (9.4) of const integral or
8394 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008395 //
Richard Smith0cc85782011-12-15 19:20:59 +00008396 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008397 // If a non-volatile const static data member is of integral or
8398 // enumeration type, its declaration in the class definition can
8399 // specify a brace-or-equal-initializer in which every initalizer-clause
8400 // that is an assignment-expression is a constant expression. A static
8401 // data member of literal type can be declared in the class definition
8402 // with the constexpr specifier; if so, its declaration shall specify a
8403 // brace-or-equal-initializer in which every initializer-clause that is
8404 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008405
8406 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008407 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008408
Richard Smith2316cd82011-09-29 19:11:37 +00008409 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008410 // type. We separately check that every constexpr variable is of literal
8411 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008412 } else if (VDecl->isConstexpr()) {
8413
John McCalldb768922010-09-10 23:21:22 +00008414 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008415 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008416 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8417 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008418 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008419
8420 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008421 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008422 // Check whether the expression is a constant expression.
8423 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008424 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008425 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008426 // in-class initializer cannot be volatile.
8427 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8428 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008429 ; // Nothing to check.
8430 else if (Init->isIntegerConstantExpr(Context, &Loc))
8431 ; // Ok, it's an ICE!
8432 else if (Init->isEvaluatable(Context)) {
8433 // If we can constant fold the initializer through heroics, accept it,
8434 // but report this as a use of an extension for -pedantic.
8435 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8436 << Init->getSourceRange();
8437 } else {
8438 // Otherwise, this is some crazy unknown case. Report the issue at the
8439 // location provided by the isIntegerConstantExpr failed check.
8440 Diag(Loc, diag::err_in_class_initializer_non_constant)
8441 << Init->getSourceRange();
8442 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008443 }
8444
Richard Smith0cc85782011-12-15 19:20:59 +00008445 // We allow foldable floating-point constants as an extension.
8446 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008447 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8448 // it anyway and provide a fixit to add the 'constexpr'.
8449 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008450 Diag(VDecl->getLocation(),
8451 diag::ext_in_class_initializer_float_type_cxx11)
8452 << DclT << Init->getSourceRange();
8453 Diag(VDecl->getLocStart(),
8454 diag::note_in_class_initializer_float_type_cxx11)
8455 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008456 } else {
8457 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8458 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008459
Richard Smithcf656382013-01-25 04:22:16 +00008460 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8461 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8462 << Init->getSourceRange();
8463 VDecl->setInvalidDecl();
8464 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008465 }
Richard Smith256336d2011-09-29 23:18:34 +00008466
Richard Smith0cc85782011-12-15 19:20:59 +00008467 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008468 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008469 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008470 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008471 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8472 VDecl->setConstexpr(true);
8473
Richard Smith2316cd82011-09-29 19:11:37 +00008474 } else {
8475 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008476 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008477 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008478 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008479 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008480 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008481 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008482 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008483 VDecl->isExternC())) &&
8484 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008485 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008486
Richard Smith0cc85782011-12-15 19:20:59 +00008487 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008488 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008489 CheckForConstantInitializer(Init, DclT);
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008490 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8491 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8492 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smith774672e2013-04-15 08:07:34 +00008493 !Init->isConstantInitializer(
8494 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008495 // GNU C++98 edits for __thread, [basic.start.init]p4:
8496 // An object of thread storage duration shall not require dynamic
8497 // initialization.
8498 // FIXME: Need strict checking here.
8499 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8500 if (getLangOpts().CPlusPlus11)
8501 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8502 }
Steve Naroff61091402007-09-12 14:07:44 +00008503 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008504
Sebastian Redla9351792012-02-11 23:51:47 +00008505 // We will represent direct-initialization similarly to copy-initialization:
8506 // int x(1); -as-> int x = 1;
8507 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8508 //
8509 // Clients that want to distinguish between the two forms, can check for
8510 // direct initializer using VarDecl::getInitStyle().
8511 // A major benefit is that clients that don't particularly care about which
8512 // exactly form was it (like the CodeGen) can handle both cases without
8513 // special case code.
8514
8515 // C++ 8.5p11:
8516 // The form of initialization (using parentheses or '=') is generally
8517 // insignificant, but does matter when the entity being initialized has a
8518 // class type.
8519 if (CXXDirectInit) {
8520 assert(DirectInit && "Call-style initializer must be direct init.");
8521 VDecl->setInitStyle(VarDecl::CallInit);
8522 } else if (DirectInit) {
8523 // This must be list-initialization. No other way is direct-initialization.
8524 VDecl->setInitStyle(VarDecl::ListInit);
8525 }
8526
John McCall8b7fd8f12011-01-19 11:48:09 +00008527 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008528}
8529
John McCalleae5acb2010-03-31 02:13:20 +00008530/// ActOnInitializerError - Given that there was an error parsing an
8531/// initializer for the given declaration, try to return to some form
8532/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008533void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008534 // Our main concern here is re-establishing invariants like "a
8535 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008536 if (!D || D->isInvalidDecl()) return;
8537
8538 VarDecl *VD = dyn_cast<VarDecl>(D);
8539 if (!VD) return;
8540
Richard Smith30482bc2011-02-20 03:19:35 +00008541 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008542 if (ParsingInitForAutoVars.count(D)) {
8543 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008544 return;
8545 }
8546
John McCalleae5acb2010-03-31 02:13:20 +00008547 QualType Ty = VD->getType();
8548 if (Ty->isDependentType()) return;
8549
8550 // Require a complete type.
8551 if (RequireCompleteType(VD->getLocation(),
8552 Context.getBaseElementType(Ty),
8553 diag::err_typecheck_decl_incomplete_type)) {
8554 VD->setInvalidDecl();
8555 return;
8556 }
8557
8558 // Require an abstract type.
8559 if (RequireNonAbstractType(VD->getLocation(), Ty,
8560 diag::err_abstract_type_in_decl,
8561 AbstractVariableType)) {
8562 VD->setInvalidDecl();
8563 return;
8564 }
8565
8566 // Don't bother complaining about constructors or destructors,
8567 // though.
8568}
8569
John McCall48871652010-08-21 09:40:31 +00008570void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008571 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008572 // If there is no declaration, there was an error parsing it. Just ignore it.
8573 if (RealDecl == 0)
8574 return;
8575
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008576 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8577 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008578
Richard Smithf0215fe2011-12-25 21:17:58 +00008579 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008580 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008581 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8582 << Var->getDeclName() << Type;
8583 Var->setInvalidDecl();
8584 return;
8585 }
Mike Stump11289f42009-09-09 15:08:12 +00008586
Richard Smithf0215fe2011-12-25 21:17:58 +00008587 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008588 // the constexpr specifier; if so, its declaration shall specify
8589 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008590 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8591 // the definition of a variable [...] or the declaration of a static data
8592 // member.
8593 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8594 if (Var->isStaticDataMember())
8595 Diag(Var->getLocation(),
8596 diag::err_constexpr_static_mem_var_requires_init)
8597 << Var->getDeclName();
8598 else
8599 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008600 Var->setInvalidDecl();
8601 return;
8602 }
8603
Joey Gouly96b94e62014-01-03 14:16:55 +00008604 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8605 // be initialized.
8606 if (!Var->isInvalidDecl() &&
8607 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
8608 !Var->getInit()) {
8609 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8610 Var->setInvalidDecl();
8611 return;
8612 }
8613
Douglas Gregore6565622010-02-09 07:26:29 +00008614 switch (Var->isThisDeclarationADefinition()) {
8615 case VarDecl::Definition:
8616 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8617 break;
8618
8619 // We have an out-of-line definition of a static data member
8620 // that has an in-class initializer, so we type-check this like
8621 // a declaration.
8622 //
8623 // Fall through
8624
8625 case VarDecl::DeclarationOnly:
8626 // It's only a declaration.
8627
8628 // Block scope. C99 6.7p7: If an identifier for an object is
8629 // declared with no linkage (C99 6.2.2p6), the type for the
8630 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008631 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008632 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008633 RequireCompleteType(Var->getLocation(), Type,
8634 diag::err_typecheck_decl_incomplete_type))
8635 Var->setInvalidDecl();
8636
8637 // Make sure that the type is not abstract.
8638 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8639 RequireNonAbstractType(Var->getLocation(), Type,
8640 diag::err_abstract_type_in_decl,
8641 AbstractVariableType))
8642 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008643 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008644 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008645 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008646 Diag(Var->getLocation(), diag::note_private_extern);
8647 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008648
Douglas Gregore6565622010-02-09 07:26:29 +00008649 return;
8650
8651 case VarDecl::TentativeDefinition:
8652 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8653 // object that has file scope without an initializer, and without a
8654 // storage-class specifier or with the storage-class specifier "static",
8655 // constitutes a tentative definition. Note: A tentative definition with
8656 // external linkage is valid (C99 6.2.2p5).
8657 if (!Var->isInvalidDecl()) {
8658 if (const IncompleteArrayType *ArrayT
8659 = Context.getAsIncompleteArrayType(Type)) {
8660 if (RequireCompleteType(Var->getLocation(),
8661 ArrayT->getElementType(),
8662 diag::err_illegal_decl_array_incomplete_type))
8663 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008664 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008665 // C99 6.9.2p3: If the declaration of an identifier for an object is
8666 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8667 // declared type shall not be an incomplete type.
8668 // NOTE: code such as the following
8669 // static struct s;
8670 // struct s { int a; };
8671 // is accepted by gcc. Hence here we issue a warning instead of
8672 // an error and we do not invalidate the static declaration.
8673 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008674 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008675 RequireCompleteType(Var->getLocation(), Type,
8676 diag::ext_typecheck_decl_incomplete_type);
8677 }
8678 }
8679
8680 // Record the tentative definition; we're done.
8681 if (!Var->isInvalidDecl())
8682 TentativeDefinitions.push_back(Var);
8683 return;
8684 }
8685
8686 // Provide a specific diagnostic for uninitialized variable
8687 // definitions with incomplete array type.
8688 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008689 Diag(Var->getLocation(),
8690 diag::err_typecheck_incomplete_array_needs_initializer);
8691 Var->setInvalidDecl();
8692 return;
8693 }
8694
John McCalla755f0f2010-08-01 01:25:24 +00008695 // Provide a specific diagnostic for uninitialized variable
8696 // definitions with reference type.
8697 if (Type->isReferenceType()) {
8698 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8699 << Var->getDeclName()
8700 << SourceRange(Var->getLocation(), Var->getLocation());
8701 Var->setInvalidDecl();
8702 return;
8703 }
Douglas Gregore6565622010-02-09 07:26:29 +00008704
8705 // Do not attempt to type-check the default initializer for a
8706 // variable with dependent type.
8707 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008708 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008709
Douglas Gregore6565622010-02-09 07:26:29 +00008710 if (Var->isInvalidDecl())
8711 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008712
Douglas Gregore6565622010-02-09 07:26:29 +00008713 if (RequireCompleteType(Var->getLocation(),
8714 Context.getBaseElementType(Type),
8715 diag::err_typecheck_decl_incomplete_type)) {
8716 Var->setInvalidDecl();
8717 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008718 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008719
Douglas Gregore6565622010-02-09 07:26:29 +00008720 // The variable can not have an abstract class type.
8721 if (RequireNonAbstractType(Var->getLocation(), Type,
8722 diag::err_abstract_type_in_decl,
8723 AbstractVariableType)) {
8724 Var->setInvalidDecl();
8725 return;
8726 }
8727
Douglas Gregor9574af62011-05-21 17:52:48 +00008728 // Check for jumps past the implicit initializer. C++0x
8729 // clarifies that this applies to a "variable with automatic
8730 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008731 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008732 // A program that jumps from a point where a variable with automatic
8733 // storage duration is not in scope to a point where it is in scope is
8734 // ill-formed unless the variable has scalar type, class type with a
8735 // trivial default constructor and a trivial destructor, a cv-qualified
8736 // version of one of these types, or an array of one of the preceding
8737 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008738 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008739 if (const RecordType *Record
8740 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008741 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008742 // Mark the function for further checking even if the looser rules of
8743 // C++11 do not require such checks, so that we can diagnose
8744 // incompatibilities with C++98.
8745 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008746 getCurFunction()->setHasBranchProtectedScope();
8747 }
Douglas Gregore6565622010-02-09 07:26:29 +00008748 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008749
8750 // C++03 [dcl.init]p9:
8751 // If no initializer is specified for an object, and the
8752 // object is of (possibly cv-qualified) non-POD class type (or
8753 // array thereof), the object shall be default-initialized; if
8754 // the object is of const-qualified type, the underlying class
8755 // type shall have a user-declared default
8756 // constructor. Otherwise, if no initializer is specified for
8757 // a non- static object, the object and its subobjects, if
8758 // any, have an indeterminate initial value); if the object
8759 // or any of its subobjects are of const-qualified type, the
8760 // program is ill-formed.
8761 // C++0x [dcl.init]p11:
8762 // If no initializer is specified for an object, the object is
8763 // default-initialized; [...].
8764 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8765 InitializationKind Kind
8766 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008767
8768 InitializationSequence InitSeq(*this, Entity, Kind, None);
8769 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008770 if (Init.isInvalid())
8771 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008772 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008773 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008774 // This is important for template substitution.
8775 Var->setInitStyle(VarDecl::CallInit);
8776 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008777
John McCall8b7fd8f12011-01-19 11:48:09 +00008778 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008779 }
8780}
8781
Richard Smith02e85f32011-04-14 22:09:26 +00008782void Sema::ActOnCXXForRangeDecl(Decl *D) {
8783 VarDecl *VD = dyn_cast<VarDecl>(D);
8784 if (!VD) {
8785 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8786 D->setInvalidDecl();
8787 return;
8788 }
8789
8790 VD->setCXXForRangeDecl(true);
8791
8792 // for-range-declaration cannot be given a storage class specifier.
8793 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008794 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008795 case SC_None:
8796 break;
8797 case SC_Extern:
8798 Error = 0;
8799 break;
8800 case SC_Static:
8801 Error = 1;
8802 break;
8803 case SC_PrivateExtern:
8804 Error = 2;
8805 break;
8806 case SC_Auto:
8807 Error = 3;
8808 break;
8809 case SC_Register:
8810 Error = 4;
8811 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008812 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008813 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008814 }
Richard Smith2316cd82011-09-29 19:11:37 +00008815 if (VD->isConstexpr())
8816 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008817 if (Error != -1) {
8818 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8819 << VD->getDeclName() << Error;
8820 D->setInvalidDecl();
8821 }
8822}
8823
John McCall8b7fd8f12011-01-19 11:48:09 +00008824void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8825 if (var->isInvalidDecl()) return;
8826
John McCall31168b02011-06-15 23:02:42 +00008827 // In ARC, don't allow jumps past the implicit initialization of a
8828 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008829 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008830 var->hasLocalStorage()) {
8831 switch (var->getType().getObjCLifetime()) {
8832 case Qualifiers::OCL_None:
8833 case Qualifiers::OCL_ExplicitNone:
8834 case Qualifiers::OCL_Autoreleasing:
8835 break;
8836
8837 case Qualifiers::OCL_Weak:
8838 case Qualifiers::OCL_Strong:
8839 getCurFunction()->setHasBranchProtectedScope();
8840 break;
8841 }
8842 }
8843
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008844 if (var->isThisDeclarationADefinition() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008845 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimek5704e4e2012-12-12 13:26:54 +00008846 getDiagnostics().getDiagnosticLevel(
8847 diag::warn_missing_variable_declarations,
8848 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008849 // Find a previous declaration that's not a definition.
8850 VarDecl *prev = var->getPreviousDecl();
8851 while (prev && prev->isThisDeclarationADefinition())
8852 prev = prev->getPreviousDecl();
8853
8854 if (!prev)
8855 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8856 }
8857
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008858 if (var->getTLSKind() == VarDecl::TLS_Static &&
8859 var->getType().isDestructedType()) {
8860 // GNU C++98 edits for __thread, [basic.start.term]p3:
8861 // The type of an object with thread storage duration shall not
8862 // have a non-trivial destructor.
8863 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8864 if (getLangOpts().CPlusPlus11)
8865 Diag(var->getLocation(), diag::note_use_thread_local);
8866 }
8867
John McCall8b7fd8f12011-01-19 11:48:09 +00008868 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008869 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008870
Richard Smithde63d362012-11-09 23:03:14 +00008871 QualType type = var->getType();
8872 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008873
8874 // __block variables might require us to capture a copy-initializer.
8875 if (var->hasAttr<BlocksAttr>()) {
8876 // It's currently invalid to ever have a __block variable with an
8877 // array type; should we diagnose that here?
8878
8879 // Regardless, we don't want to ignore array nesting when
8880 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00008881 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00008882 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00008883 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00008884 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00008885 ExprResult result
8886 = PerformMoveOrCopyInitialization(
8887 InitializedEntity::InitializeBlock(poi, type, false),
8888 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00008889 if (!result.isInvalid()) {
8890 result = MaybeCreateExprWithCleanups(result);
8891 Expr *init = result.takeAs<Expr>();
8892 Context.setBlockVarCopyInits(var, init);
8893 }
8894 }
8895 }
8896
Richard Smitheda3c842011-11-07 22:16:17 +00008897 Expr *Init = var->getInit();
8898 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00008899 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00008900
Richard Smithbf830092012-10-29 18:26:47 +00008901 if (!var->getDeclContext()->isDependentContext() &&
8902 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008903 if (IsGlobal && !var->isConstexpr() &&
8904 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8905 var->getLocation())
Eli Friedman4c27ac22013-07-16 22:40:53 +00008906 != DiagnosticsEngine::Ignored) {
8907 // Warn about globals which don't have a constant initializer. Don't
8908 // warn about globals with a non-trivial destructor because we already
8909 // warned about them.
8910 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8911 if (!(RD && !RD->hasTrivialDestructor()) &&
8912 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8913 Diag(var->getLocation(), diag::warn_global_constructor)
8914 << Init->getSourceRange();
8915 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00008916
Richard Smithd0b4dd62011-12-19 06:19:21 +00008917 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008918 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00008919 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8920 SourceLocation DiagLoc = var->getLocation();
8921 // If the note doesn't add any useful information other than a source
8922 // location, fold it into the primary diagnostic.
8923 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8924 diag::note_invalid_subexpr_in_const_expr) {
8925 DiagLoc = Notes[0].first;
8926 Notes.clear();
8927 }
8928 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8929 << var << Init->getSourceRange();
8930 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8931 Diag(Notes[I].first, Notes[I].second);
8932 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00008933 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008934 // Check whether the initializer of a const variable of integral or
8935 // enumeration type is an ICE now, since we can't tell whether it was
8936 // initialized by a constant expression if we check later.
8937 var->checkInitIsICE();
8938 }
Richard Smitheda3c842011-11-07 22:16:17 +00008939 }
John McCall8b7fd8f12011-01-19 11:48:09 +00008940
8941 // Require the destructor.
8942 if (const RecordType *recordType = baseType->getAs<RecordType>())
8943 FinalizeVarWithDestructor(var, recordType);
8944}
8945
Richard Smithb2bc2e62011-02-21 20:05:19 +00008946/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8947/// any semantic actions necessary after any initializer has been attached.
8948void
8949Sema::FinalizeDeclaration(Decl *ThisDecl) {
8950 // Note that we are no longer parsing the initializer for this declaration.
8951 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008952
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008953 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00008954 if (!VD)
8955 return;
8956
Rafael Espindola87198cd2013-08-16 23:18:50 +00008957 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8958 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00008959 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00008960 VD->dropAttr<UsedAttr>();
8961 }
8962 }
8963
Rafael Espindolad53ffa02013-10-22 21:39:03 +00008964 if (!VD->isInvalidDecl() &&
8965 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8966 if (const VarDecl *Def = VD->getDefinition()) {
8967 if (Def->hasAttr<AliasAttr>()) {
8968 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8969 << VD->getDeclName();
8970 Diag(Def->getLocation(), diag::note_previous_definition);
8971 VD->setInvalidDecl();
8972 }
8973 }
8974 }
8975
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008976 const DeclContext *DC = VD->getDeclContext();
8977 // If there's a #pragma GCC visibility in scope, and this isn't a class
8978 // member, set the visibility of this variable.
Rafael Espindola3ae00052013-05-13 00:12:11 +00008979 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008980 AddPushedVisibilityAttribute(VD);
8981
Rafael Espindolad2ecc132013-01-03 04:29:20 +00008982 if (VD->isFileVarDecl())
8983 MarkUnusedFileScopedDecl(VD);
8984
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008985 // Now we have parsed the initializer and can update the table of magic
8986 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00008987 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8988 !VD->getType()->isIntegralOrEnumerationType())
8989 return;
8990
8991 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8992 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8993 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8994 I != E; ++I) {
8995 const Expr *MagicValueExpr = VD->getInit();
8996 if (!MagicValueExpr) {
8997 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008998 }
Rafael Espindola60470f12013-01-03 04:05:19 +00008999 llvm::APSInt MagicValueInt;
9000 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9001 Diag(I->getRange().getBegin(),
9002 diag::err_type_tag_for_datatype_not_ice)
9003 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9004 continue;
9005 }
9006 if (MagicValueInt.getActiveBits() > 64) {
9007 Diag(I->getRange().getBegin(),
9008 diag::err_type_tag_for_datatype_too_large)
9009 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9010 continue;
9011 }
9012 uint64_t MagicValue = MagicValueInt.getZExtValue();
9013 RegisterTypeTagForDatatype(I->getArgumentKind(),
9014 MagicValue,
9015 I->getMatchingCType(),
9016 I->getLayoutCompatible(),
9017 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009018 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00009019}
9020
Rafael Espindolaab417692013-07-09 12:05:01 +00009021Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9022 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009023 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009024
9025 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00009026 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009027
David Majnemer50ce8352013-09-17 23:57:10 +00009028 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009029 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00009030 if (Decl *D = Group[i]) {
9031 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9032 if (!FirstDeclaratorInGroup)
9033 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00009034 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00009035 }
Richard Smith2abf6762011-02-23 00:37:57 +00009036
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009037 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00009038 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009039 HandleTagNumbering(*this, Tag);
David Majnemer50ce8352013-09-17 23:57:10 +00009040 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9041 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9042 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009043 }
David Blaikie095deba2012-11-14 01:52:05 +00009044
Rafael Espindolaab417692013-07-09 12:05:01 +00009045 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00009046}
9047
9048/// BuildDeclaratorGroup - convert a list of declarations into a declaration
9049/// group, performing any necessary semantic checking.
9050Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00009051Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00009052 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00009053 // C++0x [dcl.spec.auto]p7:
9054 // If the type deduced for the template parameter U is not the same in each
9055 // deduction, the program is ill-formed.
9056 // FIXME: When initializer-list support is added, a distinction is needed
9057 // between the deduced type U and the deduced type which 'auto' stands for.
9058 // auto a = 0, b = { 1, 2, 3 };
9059 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009060 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009061 QualType Deduced;
9062 CanQualType DeducedCanon;
9063 VarDecl *DeducedDecl = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009064 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009065 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9066 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009067 // Don't reissue diagnostics when instantiating a template.
9068 if (AT && D->isInvalidDecl())
9069 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009070 QualType U = AT ? AT->getDeducedType() : QualType();
9071 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009072 CanQualType UCanon = Context.getCanonicalType(U);
9073 if (Deduced.isNull()) {
9074 Deduced = U;
9075 DeducedCanon = UCanon;
9076 DeducedDecl = D;
9077 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009078 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9079 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009080 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009081 << Deduced << DeducedDecl->getDeclName()
9082 << U << D->getDeclName()
9083 << DeducedDecl->getInit()->getSourceRange()
9084 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009085 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009086 break;
9087 }
9088 }
9089 }
9090 }
9091 }
9092
Rafael Espindolaab417692013-07-09 12:05:01 +00009093 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009094
Rafael Espindolaab417692013-07-09 12:05:01 +00009095 return DeclGroupPtrTy::make(
9096 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009097}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009098
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009099void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009100 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009101}
9102
Rafael Espindolaab417692013-07-09 12:05:01 +00009103void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009104 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009105 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009106 return;
9107
9108 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9109 Group[0]->getLocation())
9110 == DiagnosticsEngine::Ignored)
9111 return;
9112
Rafael Espindolaab417692013-07-09 12:05:01 +00009113 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009114 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009115 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009116 // additional declaration references:
9117 // 'typedef struct S {} S;'
9118 // 'typedef struct S *S;'
9119 // 'struct S *pS;'
9120 // FinalizeDeclaratorGroup adds these as separate declarations.
9121 Decl *MaybeTagDecl = Group[0];
9122 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009123 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009124 }
9125 }
9126
9127 // See if there are any new comments that are not attached to a decl.
9128 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9129 if (!Comments.empty() &&
9130 !Comments.back()->isAttached()) {
9131 // There is at least one comment that not attached to a decl.
9132 // Maybe it should be attached to one of these decls?
9133 //
9134 // Note that this way we pick up not only comments that precede the
9135 // declaration, but also comments that *follow* the declaration -- thanks to
9136 // the lookahead in the lexer: we've consumed the semicolon and looked
9137 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009138 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009139 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009140 }
9141}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009142
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009143/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9144/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009145Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009146 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009147
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009148 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009149
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009150 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009151 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009152 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009153 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009154 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009155 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9156 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009157 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009158 Diag(DS.getStorageClassSpecLoc(),
9159 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009160 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009161 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009162
Richard Smithb4a9e862013-04-12 22:46:28 +00009163 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9164 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9165 << DeclSpec::getSpecifierName(TSCS);
9166 if (DS.isConstexprSpecified())
9167 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009168 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009169
Richard Smithb4a9e862013-04-12 22:46:28 +00009170 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009171
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009172 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009173 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009174
David Blaikiebbafb8a2012-03-11 07:00:24 +00009175 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009176 // Check that there are no default arguments inside the type of this
9177 // parameter.
9178 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009179
9180 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9181 if (D.getCXXScopeSpec().isSet()) {
9182 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9183 << D.getCXXScopeSpec().getRange();
9184 D.getCXXScopeSpec().clear();
9185 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009186 }
9187
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009188 // Ensure we have a valid name
9189 IdentifierInfo *II = 0;
9190 if (D.hasName()) {
9191 II = D.getIdentifier();
9192 if (!II) {
9193 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009194 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009195 D.setInvalidType(true);
9196 }
9197 }
9198
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009199 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009200 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009201 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9202 ForRedeclaration);
9203 LookupName(R, S);
9204 if (R.isSingleResult()) {
9205 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009206 if (PrevDecl->isTemplateParameter()) {
9207 // Maybe we will complain about the shadowed template parameter.
9208 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9209 // Just pretend that we didn't see the previous declaration.
9210 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00009211 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009212 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009213 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009214
Chris Lattnerd9773512009-01-21 02:38:50 +00009215 // Recover by removing the name
9216 II = 0;
9217 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009218 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009219 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009220 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009221 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009222
John McCallf7b2fb52010-01-22 00:28:27 +00009223 // Temporarily put parameter variables in the translation unit, not
9224 // the enclosing context. This prevents them from accidentally
9225 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009226 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009227 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009228 D.getIdentifierLoc(), II,
9229 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009230 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009231
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009232 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009233 New->setInvalidDecl();
9234
9235 assert(S->isFunctionPrototypeScope());
9236 assert(S->getFunctionPrototypeDepth() >= 1);
9237 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9238 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009239
Douglas Gregor91f84212008-12-11 16:49:14 +00009240 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009241 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009242 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009243 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009244
Douglas Gregor758a8692009-06-17 21:51:59 +00009245 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009246
Douglas Gregor41866812011-09-12 18:37:38 +00009247 if (D.getDeclSpec().isModulePrivateSpecified())
9248 Diag(New->getLocation(), diag::err_module_private_local)
9249 << 1 << New->getDeclName()
9250 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9251 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9252
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009253 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009254 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9255 }
John McCall48871652010-08-21 09:40:31 +00009256 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009257}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009258
John McCalla3ccba02010-06-04 11:21:44 +00009259/// \brief Synthesizes a variable for a parameter arising from a
9260/// typedef.
9261ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9262 SourceLocation Loc,
9263 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009264 /* FIXME: setting StartLoc == Loc.
9265 Would it be worth to modify callers so as to provide proper source
9266 location for the unnamed parameters, embedding the parameter's type? */
9267 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00009268 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009269 SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00009270 Param->setImplicit();
9271 return Param;
9272}
9273
John McCallc5990642010-08-24 09:05:15 +00009274void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9275 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009276 // Don't diagnose unused-parameter errors in template instantiations; we
9277 // will already have done so in the template itself.
9278 if (!ActiveTemplateInstantiations.empty())
9279 return;
9280
9281 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009282 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009283 !(*Param)->hasAttr<UnusedAttr>()) {
9284 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9285 << (*Param)->getDeclName();
9286 }
9287 }
9288}
9289
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009290void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9291 ParmVarDecl * const *ParamEnd,
9292 QualType ReturnTy,
9293 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009294 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009295 return;
9296
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009297 // Warn if the return value is pass-by-value and larger than the specified
9298 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009299 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009300 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009301 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009302 Diag(D->getLocation(), diag::warn_return_value_size)
9303 << D->getDeclName() << Size;
9304 }
9305
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009306 // Warn if any parameter is pass-by-value and larger than the specified
9307 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009308 for (; Param != ParamEnd; ++Param) {
9309 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009310 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009311 continue;
9312 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009313 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009314 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9315 << (*Param)->getDeclName() << Size;
9316 }
9317}
9318
Abramo Bagnaradff19302011-03-08 08:55:46 +00009319ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9320 SourceLocation NameLoc, IdentifierInfo *Name,
9321 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009322 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009323 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009324 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009325 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009326 T->isObjCLifetimeType()) {
9327
9328 Qualifiers::ObjCLifetime lifetime;
9329
9330 // Special cases for arrays:
9331 // - if it's const, use __unsafe_unretained
9332 // - otherwise, it's an error
9333 if (T->isArrayType()) {
9334 if (!T.isConstQualified()) {
9335 DelayedDiagnostics.add(
9336 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009337 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009338 }
9339 lifetime = Qualifiers::OCL_ExplicitNone;
9340 } else {
9341 lifetime = T->getObjCARCImplicitLifetime();
9342 }
9343 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009344 }
9345
Abramo Bagnaradff19302011-03-08 08:55:46 +00009346 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009347 Context.getAdjustedParameterType(T),
9348 TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009349 StorageClass, 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00009350
9351 // Parameters can not be abstract class types.
9352 // For record types, this is done by the AbstractClassUsageDiagnoser once
9353 // the class has been completely parsed.
9354 if (!CurContext->isRecord() &&
9355 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9356 AbstractParamType))
9357 New->setInvalidDecl();
9358
9359 // Parameter declarators cannot be interface types. All ObjC objects are
9360 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009361 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009362 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009363 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009364 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009365 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009366 T = Context.getObjCObjectPointerType(T);
9367 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009368 }
9369
9370 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9371 // duration shall not be qualified by an address-space qualifier."
9372 // Since all parameters have automatic store duration, they can not have
9373 // an address space.
9374 if (T.getAddressSpace() != 0) {
9375 Diag(NameLoc, diag::err_arg_with_address_space);
9376 New->setInvalidDecl();
9377 }
9378
9379 return New;
9380}
9381
Douglas Gregor170512f2009-04-01 23:51:29 +00009382void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9383 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009384 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009385
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009386 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9387 // for a K&R function.
9388 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009389 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9390 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009391 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009392 SmallString<256> Code;
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009393 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00009394 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009395 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00009396 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00009397 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00009398 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009399
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009400 // Implicitly declare the argument as type 'int' for lack of a better
9401 // type.
John McCall084e83d2011-03-24 11:26:52 +00009402 AttributeFactory attrs;
9403 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009404 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009405 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00009406 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00009407 PrevSpec, DiagID);
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009408 // Use the identifier location for the type source range.
9409 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9410 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009411 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9412 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00009413 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009414 }
9415 }
Mike Stump11289f42009-09-09 15:08:12 +00009416 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009417}
9418
Richard Smith79a52e52012-04-17 22:30:01 +00009419Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00009420 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009421 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009422 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009423
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009424 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009425 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009426 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009427}
9428
Anders Carlsson2a45e402012-12-18 01:29:20 +00009429static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9430 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009431 // Don't warn about invalid declarations.
9432 if (FD->isInvalidDecl())
9433 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009434
Anders Carlsson31c7e882009-12-09 03:30:09 +00009435 // Or declarations that aren't global.
9436 if (!FD->isGlobal())
9437 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009438
Anders Carlsson31c7e882009-12-09 03:30:09 +00009439 // Don't warn about C++ member functions.
9440 if (isa<CXXMethodDecl>(FD))
9441 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009442
Anders Carlsson31c7e882009-12-09 03:30:09 +00009443 // Don't warn about 'main'.
9444 if (FD->isMain())
9445 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009446
Anders Carlsson31c7e882009-12-09 03:30:09 +00009447 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009448 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009449 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009450
9451 // Don't warn about function templates.
9452 if (FD->getDescribedFunctionTemplate())
9453 return false;
9454
9455 // Don't warn about function template specializations.
9456 if (FD->isFunctionTemplateSpecialization())
9457 return false;
9458
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009459 // Don't warn for OpenCL kernels.
9460 if (FD->hasAttr<OpenCLKernelAttr>())
9461 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009462
Anders Carlsson31c7e882009-12-09 03:30:09 +00009463 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009464 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9465 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009466 // Ignore any declarations that occur in function or method
9467 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009468 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009469 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009470
Anders Carlsson31c7e882009-12-09 03:30:09 +00009471 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009472 if (FD->getNumParams() == 0)
9473 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009474 break;
9475 }
Richard Smith541b38b2013-09-20 01:15:31 +00009476
Anders Carlsson31c7e882009-12-09 03:30:09 +00009477 return MissingPrototype;
9478}
9479
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009480void
9481Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9482 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009483 // Don't complain if we're in GNU89 mode and the previous definition
9484 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009485 const FunctionDecl *Definition = EffectiveDefinition;
9486 if (!Definition)
9487 if (!FD->isDefined(Definition))
9488 return;
9489
9490 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009491 return;
9492
9493 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9494 Definition->getStorageClass() == SC_Extern)
9495 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009496 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009497 else
9498 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9499
9500 Diag(Definition->getLocation(), diag::note_previous_definition);
9501 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009502}
Faisal Valia17d19f2013-11-07 05:17:06 +00009503
9504
Faisal Valic1a6dc42013-10-23 16:10:50 +00009505static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9506 Sema &S) {
9507 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009508
9509 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009510 LSI->CallOperator = CallOperator;
9511 LSI->Lambda = LambdaClass;
9512 LSI->ReturnType = CallOperator->getResultType();
9513 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9514
9515 if (LCD == LCD_None)
9516 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9517 else if (LCD == LCD_ByCopy)
9518 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9519 else if (LCD == LCD_ByRef)
9520 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9521 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9522
9523 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9524 LSI->Mutable = !CallOperator->isConst();
9525
Faisal Valia17d19f2013-11-07 05:17:06 +00009526 // Add the captures to the LSI so they can be noted as already
9527 // captured within tryCaptureVar.
9528 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9529 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9530 if (C->capturesVariable()) {
9531 VarDecl *VD = C->getCapturedVar();
9532 if (VD->isInitCapture())
9533 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9534 QualType CaptureType = VD->getType();
9535 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9536 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9537 /*RefersToEnclosingLocal*/true, C->getLocation(),
9538 /*EllipsisLoc*/C->isPackExpansion()
9539 ? C->getEllipsisLoc() : SourceLocation(),
9540 CaptureType, /*Expr*/ 0);
9541
9542 } else if (C->capturesThis()) {
9543 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9544 S.getCurrentThisType(), /*Expr*/ 0);
9545 }
9546 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009547}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009548
John McCall48871652010-08-21 09:40:31 +00009549Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009550 // Clear the last template instantiation error context.
9551 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9552
Douglas Gregor17a7c122009-06-24 00:54:41 +00009553 if (!D)
9554 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009555 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009556
John McCall48871652010-08-21 09:40:31 +00009557 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009558 FD = FunTmpl->getTemplatedDecl();
9559 else
John McCall48871652010-08-21 09:40:31 +00009560 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009561 // If we are instantiating a generic lambda call operator, push
9562 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009563 // that's already been calculated (ActOnLambdaExpr) to prime the current
9564 // LambdaScopeInfo.
9565 // When the template operator is being specialized, the LambdaScopeInfo,
9566 // has to be properly restored so that tryCaptureVariable doesn't try
9567 // and capture any new variables. In addition when calculating potential
9568 // captures during transformation of nested lambdas, it is necessary to
9569 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009570 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009571 assert(ActiveTemplateInstantiations.size() &&
9572 "There should be an active template instantiation on the stack "
9573 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009574 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009575 }
9576 else
9577 // Enter a new function scope
9578 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009579
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009580 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009581 if (!FD->isLateTemplateParsed())
9582 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009583
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009584 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009585 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009586 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9587 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009588 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009589 FD->setInvalidDecl();
9590 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009591 }
9592
Eli Friedman9ad72442009-03-04 07:30:59 +00009593 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009594 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9595 QualType ResultType = FD->getResultType();
9596 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009597 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009598 RequireCompleteType(FD->getLocation(), ResultType,
9599 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009600 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009601
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009602 // GNU warning -Wmissing-prototypes:
9603 // Warn if a global function is defined without a previous
9604 // prototype declaration. This warning is issued even if the
9605 // definition itself provides a prototype. The aim is to detect
9606 // global functions that fail to be declared in header files.
Anders Carlsson2a45e402012-12-18 01:29:20 +00009607 const FunctionDecl *PossibleZeroParamPrototype = 0;
9608 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009609 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009610
Anders Carlsson2a45e402012-12-18 01:29:20 +00009611 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009612 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009613 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009614 if (TypeSourceInfo *TI =
9615 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9616 TypeLoc TL = TI->getTypeLoc();
9617 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9618 Diag(PossibleZeroParamPrototype->getLocation(),
9619 diag::note_declaration_not_a_prototype)
9620 << PossibleZeroParamPrototype
9621 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9622 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009623 }
9624 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009625
Douglas Gregor67da0d92009-05-15 17:59:04 +00009626 if (FnBodyScope)
9627 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009628
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009629 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009630 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9631 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009632
9633 // Introduce our parameters into the function scope
9634 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9635 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00009636 Param->setOwningFunction(FD);
9637
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009638 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009639 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009640 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009641
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009642 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009643 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009644 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009645
James Molloy6f8780b2012-02-29 10:24:19 +00009646 // If we had any tags defined in the function prototype,
9647 // introduce them into the function scope.
9648 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009649 for (ArrayRef<NamedDecl *>::iterator
9650 I = FD->getDeclsInPrototypeScope().begin(),
9651 E = FD->getDeclsInPrototypeScope().end();
9652 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009653 NamedDecl *D = *I;
9654
9655 // Some of these decls (like enums) may have been pinned to the translation unit
9656 // for lack of a real context earlier. If so, remove from the translation unit
9657 // and reattach to the current context.
9658 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9659 // Is the decl actually in the context?
9660 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9661 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9662 if (*DI == D) {
9663 Context.getTranslationUnitDecl()->removeDecl(D);
9664 break;
9665 }
9666 }
9667 // Either way, reassign the lexical decl context to our FunctionDecl.
9668 D->setLexicalDeclContext(CurContext);
9669 }
9670
9671 // If the decl has a non-null name, make accessible in the current scope.
9672 if (!D->getName().empty())
9673 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9674
9675 // Similarly, dive into enums and fish their constants out, making them
9676 // accessible in this scope.
9677 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9678 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9679 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie40ed2972012-06-06 20:45:41 +00009680 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009681 }
9682 }
9683 }
9684
Richard Smith79a52e52012-04-17 22:30:01 +00009685 // Ensure that the function's exception specification is instantiated.
9686 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9687 ResolveExceptionSpec(D->getLocation(), FPT);
9688
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009689 // Checking attributes of current function definition
9690 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009691 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
Aaron Ballman9ead1242013-12-19 02:39:40 +00009692 if (DA && (!FD->hasAttr<DLLExportAttr>())) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009693 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00009694 // Microsoft accepts dllimport for functions defined within class scope.
9695 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00009696 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009697 Diag(FD->getLocation(),
9698 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
Aaron Ballman3e424b52013-12-26 18:30:57 +00009699 << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009700 FD->setInvalidDecl();
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009701 return D;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00009702 }
9703
9704 // Visual C++ appears to not think this is an issue, so only issue
9705 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00009706 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009707 // If a symbol previously declared dllimport is later defined, the
9708 // attribute is ignored in subsequent references, and a warning is
9709 // emitted.
9710 Diag(FD->getLocation(),
9711 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Aaron Ballman44ebc072014-01-02 22:29:41 +00009712 << FD << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009713 }
9714 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009715 // We want to attach documentation to original Decl (which might be
9716 // a function template).
9717 ActOnDocumentableDecl(D);
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009718 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009719}
9720
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009721/// \brief Given the set of return statements within a function body,
9722/// compute the variables that are subject to the named return value
9723/// optimization.
9724///
9725/// Each of the variables that is subject to the named return value
9726/// optimization will be marked as NRVO variables in the AST, and any
9727/// return statement that has a marked NRVO variable as its NRVO candidate can
9728/// use the named return value optimization.
9729///
9730/// This function applies a very simplistic algorithm for NRVO: if every return
9731/// statement in the function has the same NRVO candidate, that candidate is
9732/// the NRVO variable.
9733///
9734/// FIXME: Employ a smarter algorithm that accounts for multiple return
9735/// statements and the lifetimes of the NRVO candidates. We should be able to
9736/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00009737void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009738 ReturnStmt **Returns = Scope->Returns.data();
9739
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009740 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00009741 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009742 if (!Returns[I]->getNRVOCandidate())
9743 return;
9744
9745 if (!NRVOCandidate)
9746 NRVOCandidate = Returns[I]->getNRVOCandidate();
9747 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9748 return;
9749 }
9750
9751 if (NRVOCandidate)
9752 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9753}
9754
Richard Smith1ab34b32012-11-19 21:13:18 +00009755bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith9219d1b2012-11-27 21:31:01 +00009756 if (!Consumer.shouldSkipFunctionBody(D))
9757 return false;
9758
Richard Smith1ab34b32012-11-19 21:13:18 +00009759 if (isa<ObjCMethodDecl>(D))
9760 return true;
9761
9762 FunctionDecl *FD = 0;
9763 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9764 FD = FTD->getTemplatedDecl();
9765 else
9766 FD = cast<FunctionDecl>(D);
9767
9768 // We cannot skip the body of a function (or function template) which is
9769 // constexpr, since we may need to evaluate its body in order to parse the
9770 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009771 // We cannot skip the body of a function with an undeduced return type,
9772 // because any callers of that function need to know the type.
9773 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1ab34b32012-11-19 21:13:18 +00009774}
9775
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009776Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009777 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009778 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009779 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009780 MD->setHasSkippedBody();
9781 return ActOnFinishFunctionBody(Decl, 0);
9782}
9783
John McCallfaf5fb42010-08-26 23:41:50 +00009784Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009785 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009786}
9787
John McCallb268a282010-08-23 23:25:46 +00009788Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9789 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009790 FunctionDecl *FD = 0;
9791 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9792 if (FunTmpl)
9793 FD = FunTmpl->getTemplatedDecl();
9794 else
9795 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9796
Ted Kremenek0b405322010-03-23 00:13:23 +00009797 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00009798 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00009799
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009800 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009801 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009802
Richard Smith7500ab22013-05-10 04:31:10 +00009803 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9804 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9805 // If the function has a deduced result type but contains no 'return'
9806 // statements, the result type as written must be exactly 'auto', and
9807 // the deduced result type is 'void'.
9808 if (!FD->getResultType()->getAs<AutoType>()) {
9809 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9810 << FD->getResultType();
9811 FD->setInvalidDecl();
9812 } else {
9813 // Substitute 'void' for the 'auto' in the type.
9814 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9815 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9816 Context.adjustDeducedFunctionResultType(
9817 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009818 }
9819 }
9820
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009821 // The only way to be included in UndefinedButUsed is if there is an
9822 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009823 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009824 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009825 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009826 UndefinedButUsed.erase(FD);
9827 else if (FD->isInlined() &&
9828 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9829 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9830 UndefinedButUsed.erase(FD);
9831 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009832
John McCall5ed3caf2012-02-14 19:50:52 +00009833 // If the function implicitly returns zero (like 'main') or is naked,
9834 // don't complain about missing return statements.
9835 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009836 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00009837
Francois Pichet3abc9b82011-05-11 02:14:46 +00009838 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +00009839 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +00009840 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +00009841 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9842
Douglas Gregor88d292c2010-05-13 16:44:06 +00009843 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009844 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009845 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9846 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009847
9848 // If this is a constructor, we need a vtable.
9849 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9850 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009851
Jordan Rosed39e5f12012-07-02 21:19:23 +00009852 // Try to apply the named return value optimization. We have to check
9853 // if we can do this here because lambdas keep return statements around
9854 // to deduce an implicit return type.
9855 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9856 !FD->isDependentContext())
9857 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00009858 }
9859
Douglas Gregor21f46922012-02-08 20:17:14 +00009860 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9861 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00009862 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00009863 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00009864 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009865 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009866 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009867 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9868 MD->getResultType(), MD);
Douglas Gregore3f3ea02011-09-06 20:33:37 +00009869
9870 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00009871 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009872 }
Jordan Rose2afd6612012-10-19 16:05:26 +00009873 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00009874 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9875 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00009876 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00009877 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009878 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9879 const ObjCMethodDecl *InitMethod = 0;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00009880 bool isDesignated =
9881 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009882 assert(isDesignated && InitMethod);
9883 (void)isDesignated;
9884 Diag(MD->getLocation(),
9885 diag::warn_objc_designated_init_missing_super_call);
9886 Diag(InitMethod->getLocation(),
9887 diag::note_objc_designated_init_marked_here);
9888 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9889 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009890 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9891 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9892 getCurFunction()->ObjCWarnForNoInitDelegation = false;
9893 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009894 } else {
John McCall48871652010-08-21 09:40:31 +00009895 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009896 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009897
Jordan Rose2afd6612012-10-19 16:05:26 +00009898 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009899 "This should only be set for ObjC methods, which should have been "
9900 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00009901
Chris Lattnere2473062007-05-28 06:28:18 +00009902 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00009903 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009904 // C++ constructors that have function-try-blocks can't have return
9905 // statements in the handlers of that block. (C++ [except.handle]p14)
9906 // Verify this.
9907 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9908 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9909
Richard Smithdef8bdb2011-08-12 18:44:32 +00009910 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00009911 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00009912 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009913 !hasAnyUnrecoverableErrorsInThisFunction() &&
9914 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00009915 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00009916
John McCalldeb646e2010-08-04 01:04:25 +00009917 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9918 if (!Destructor->getParent()->isDependentType())
9919 CheckDestructor(Destructor);
9920
John McCalla6309952010-03-16 21:39:52 +00009921 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9922 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00009923 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00009924
9925 // If any errors have occurred, clear out any temporaries that may have
9926 // been leftover. This ensures that these temporaries won't be picked up for
9927 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00009928 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00009929 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00009930 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00009931 }
9932 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9933 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00009934 // Since the body is valid, issue any analysis-based warnings that are
9935 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00009936 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00009937 }
9938
Richard Smith3607ffe2012-02-13 03:54:03 +00009939 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9940 (!CheckConstexprFunctionDecl(FD) ||
9941 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00009942 FD->setInvalidDecl();
9943
John McCall28fc7092011-11-10 05:35:25 +00009944 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00009945 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00009946 assert(MaybeODRUseExprs.empty() &&
9947 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00009948 }
9949
John McCalle99d5f32010-03-25 22:08:03 +00009950 if (!IsInstantiation)
9951 PopDeclContext();
9952
Eli Friedman71c80552012-01-05 03:35:19 +00009953 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +00009954 // If any errors have occurred, clear out any temporaries that may have
9955 // been leftover. This ensures that these temporaries won't be picked up for
9956 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00009957 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00009958 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00009959 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00009960
John McCall48871652010-08-21 09:40:31 +00009961 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00009962}
9963
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009964
9965/// When we finish delayed parsing of an attribute, we must attach it to the
9966/// relevant Decl.
9967void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9968 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00009969 // Always attach attributes to the underlying decl.
9970 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9971 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00009972 ProcessDeclAttributeList(S, D, Attrs.getList());
9973
9974 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9975 if (Method->isStatic())
9976 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009977}
9978
9979
Chris Lattnerac18be92006-11-20 06:49:47 +00009980/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9981/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00009982NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00009983 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009984 // Before we produce a declaration for an implicitly defined
9985 // function, see whether there was a locally-scoped declaration of
9986 // this name as a function or variable. If so, use that
9987 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +00009988 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9989 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9990 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9991 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009992 }
9993
Chris Lattner00e26072008-05-05 21:18:06 +00009994 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00009995 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00009996 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00009997 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009998 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00009999 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +000010000 else
Hans Wennborg70a13242011-12-08 15:56:07 +000010001 diag_id = diag::warn_implicit_function_decl;
10002 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +000010003
Hans Wennborg70a13242011-12-08 15:56:07 +000010004 // Because typo correction is expensive, only do it if the implicit
10005 // function declaration is going to be treated as an error.
10006 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10007 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000010008 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +000010009 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smithf9b15102013-08-17 00:46:16 +000010010 LookupOrdinaryName, S, 0, Validator)))
10011 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10012 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +000010013 }
10014
Chris Lattnerac18be92006-11-20 06:49:47 +000010015 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +000010016 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +000010017 AttributeFactory attrFactory;
10018 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +000010019 unsigned DiagID;
10020 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010021 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +000010022 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010023 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +000010024 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010025 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10026 /*IsAmbiguous=*/false,
10027 /*RParenLoc=*/NoLoc,
10028 /*ArgInfo=*/0,
10029 /*NumArgs=*/0,
10030 /*EllipsisLoc=*/NoLoc,
10031 /*RParenLoc=*/NoLoc,
10032 /*TypeQuals=*/0,
10033 /*RefQualifierIsLvalueRef=*/true,
10034 /*RefQualifierLoc=*/NoLoc,
10035 /*ConstQualifierLoc=*/NoLoc,
10036 /*VolatileQualifierLoc=*/NoLoc,
10037 /*MutableLoc=*/NoLoc,
10038 EST_None,
10039 /*ESpecLoc=*/NoLoc,
10040 /*Exceptions=*/0,
10041 /*ExceptionRanges=*/0,
10042 /*NumExceptions=*/0,
10043 /*NoexceptExpr=*/0,
10044 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +000010045 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010046 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +000010047 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010048
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010049 // Insert this function into translation-unit scope.
10050
10051 DeclContext *PrevDC = CurContext;
10052 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010053
Jordan Rosed03d99d2013-03-05 01:27:54 +000010054 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010055 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010056
10057 CurContext = PrevDC;
10058
Douglas Gregore711f702009-02-14 18:57:46 +000010059 AddKnownFunctionAttributes(FD);
10060
Steve Naroff3913ea42008-04-04 14:32:09 +000010061 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010062}
10063
Douglas Gregore711f702009-02-14 18:57:46 +000010064/// \brief Adds any function attributes that we know a priori based on
10065/// the declaration of this function.
10066///
10067/// These attributes can apply both to implicitly-declared builtins
10068/// (like __builtin___printf_chk) or to library-declared functions
10069/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010070///
10071/// We need to check for duplicate attributes both here and where user-written
10072/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010073void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10074 if (FD->isInvalidDecl())
10075 return;
10076
10077 // If this is a built-in function, map its builtin attributes to
10078 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010079 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010080 // Handle printf-formatting attributes.
10081 unsigned FormatIdx;
10082 bool HasVAListArg;
10083 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010084 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010085 const char *fmt = "printf";
10086 unsigned int NumParams = FD->getNumParams();
10087 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10088 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10089 fmt = "NSString";
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010090 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010091 &Context.Idents.get(fmt),
10092 FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +000010093 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010094 }
Douglas Gregore711f702009-02-14 18:57:46 +000010095 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010096 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10097 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010098 if (!FD->hasAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010099 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010100 &Context.Idents.get("scanf"),
10101 FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +000010102 HasVAListArg ? 0 : FormatIdx+2));
10103 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010104
10105 // Mark const if we don't care about errno and that is the only
10106 // thing preventing the function from being const. This allows
10107 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010108 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010109 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010110 if (!FD->hasAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010111 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010112 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010113
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010114 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010115 !FD->hasAttr<ReturnsTwiceAttr>())
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010116 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010117 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010118 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010119 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010120 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +000010121 }
10122
10123 IdentifierInfo *Name = FD->getIdentifier();
10124 if (!Name)
10125 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010126 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010127 FD->getDeclContext()->isTranslationUnit()) ||
10128 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010129 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010130 LinkageSpecDecl::lang_c)) {
10131 // Okay: this could be a libc/libm/Objective-C function we know
10132 // about.
10133 } else
10134 return;
10135
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010136 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010137 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010138 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010139 if (!FD->hasAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010140 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010141 &Context.Idents.get("printf"), 2,
Eli Friedmanf4799842009-06-10 04:01:38 +000010142 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010143 }
Jordan Rose742c6072012-08-08 21:17:31 +000010144
10145 if (Name->isStr("__CFStringMakeConstantString")) {
10146 // We already have a __builtin___CFStringMakeConstantString,
10147 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010148 if (!FD->hasAttr<FormatArgAttr>())
Jordan Rose742c6072012-08-08 21:17:31 +000010149 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10150 }
Douglas Gregore711f702009-02-14 18:57:46 +000010151}
Chris Lattner302b4be2006-11-19 02:31:38 +000010152
John McCall703a3f82009-10-24 08:00:42 +000010153TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010154 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010155 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010156 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010157
John McCallbcd03502009-12-07 02:54:59 +000010158 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010159 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010160 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010161 }
10162
Chris Lattner18b19622007-01-22 07:39:13 +000010163 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010164 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010165 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010166 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010167 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010168 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010169
John McCall04fcd0d2011-02-01 08:20:08 +000010170 // Bail out immediately if we have an invalid declaration.
10171 if (D.isInvalidType()) {
10172 NewTD->setInvalidDecl();
10173 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010174 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010175
Douglas Gregor41866812011-09-12 18:37:38 +000010176 if (D.getDeclSpec().isModulePrivateSpecified()) {
10177 if (CurContext->isFunctionOrMethod())
10178 Diag(NewTD->getLocation(), diag::err_module_private_local)
10179 << 2 << NewTD->getDeclName()
10180 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10181 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10182 else
10183 NewTD->setModulePrivate();
10184 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010185
John McCall04fcd0d2011-02-01 08:20:08 +000010186 // C++ [dcl.typedef]p8:
10187 // If the typedef declaration defines an unnamed class (or
10188 // enum), the first typedef-name declared by the declaration
10189 // to be that class type (or enum type) is used to denote the
10190 // class type (or enum type) for linkage purposes only.
10191 // We need to check whether the type was declared in the declaration.
10192 switch (D.getDeclSpec().getTypeSpecType()) {
10193 case TST_enum:
10194 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010195 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010196 case TST_union:
10197 case TST_class: {
10198 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10199
10200 // Do nothing if the tag is not anonymous or already has an
10201 // associated typedef (from an earlier typedef in this decl group).
10202 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010203 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010204
10205 // A well-formed anonymous tag must always be a TUK_Definition.
10206 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10207
10208 // The type must match the tag exactly; no qualifiers allowed.
10209 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10210 break;
10211
10212 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010213 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010214 break;
10215 }
10216
10217 default:
10218 break;
10219 }
10220
Steve Narofff93b6722007-08-28 20:14:24 +000010221 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010222}
10223
Douglas Gregord9034f02009-05-14 16:41:31 +000010224
Richard Smith4b38ded2012-03-14 23:13:10 +000010225/// \brief Check that this is a valid underlying type for an enum declaration.
10226bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10227 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10228 QualType T = TI->getType();
10229
Eli Friedman52f32b92012-12-18 02:37:32 +000010230 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010231 return false;
10232
Eli Friedman52f32b92012-12-18 02:37:32 +000010233 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10234 if (BT->isInteger())
10235 return false;
10236
Richard Smith4b38ded2012-03-14 23:13:10 +000010237 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10238 return true;
10239}
10240
10241/// Check whether this is a valid redeclaration of a previous enumeration.
10242/// \return true if the redeclaration was invalid.
10243bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10244 QualType EnumUnderlyingTy,
10245 const EnumDecl *Prev) {
10246 bool IsFixed = !EnumUnderlyingTy.isNull();
10247
10248 if (IsScoped != Prev->isScoped()) {
10249 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10250 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010251 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010252 return true;
10253 }
10254
10255 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010256 if (!EnumUnderlyingTy->isDependentType() &&
10257 !Prev->getIntegerType()->isDependentType() &&
10258 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010259 Prev->getIntegerType())) {
10260 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10261 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Toker8c44db52014-01-06 11:31:06 +000010262 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010263 return true;
10264 }
10265 } else if (IsFixed != Prev->isFixed()) {
10266 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10267 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010268 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010269 return true;
10270 }
10271
10272 return false;
10273}
10274
Joao Matosdc86f942012-08-31 18:45:21 +000010275/// \brief Get diagnostic %select index for tag kind for
10276/// redeclaration diagnostic message.
10277/// WARNING: Indexes apply to particular diagnostics only!
10278///
10279/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010280static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010281 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010282 case TTK_Struct: return 0;
10283 case TTK_Interface: return 1;
10284 case TTK_Class: return 2;
10285 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010286 }
Joao Matosdc86f942012-08-31 18:45:21 +000010287}
10288
10289/// \brief Determine if tag kind is a class-key compatible with
10290/// class for redeclaration (class, struct, or __interface).
10291///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010292/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010293static bool isClassCompatTagKind(TagTypeKind Tag)
10294{
10295 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10296}
10297
Douglas Gregord9034f02009-05-14 16:41:31 +000010298/// \brief Determine whether a tag with a given kind is acceptable
10299/// as a redeclaration of the given tag declaration.
10300///
10301/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010302bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010303 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010304 SourceLocation NewTagLoc,
10305 const IdentifierInfo &Name) {
10306 // C++ [dcl.type.elab]p3:
10307 // The class-key or enum keyword present in the
10308 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010309 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010310 // refers. This rule also applies to the form of
10311 // elaborated-type-specifier that declares a class-name or
10312 // friend class since it can be construed as referring to the
10313 // definition of the class. Thus, in any
10314 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010315 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010316 // used to refer to a union (clause 9), and either the class or
10317 // struct class-key shall be used to refer to a class (clause 9)
10318 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010319 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010320 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010321 if (OldTag == NewTag)
10322 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010323
Joao Matosdc86f942012-08-31 18:45:21 +000010324 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010325 // Warn about the struct/class tag mismatch.
10326 bool isTemplate = false;
10327 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10328 isTemplate = Record->getDescribedClassTemplate();
10329
Richard Trieucaa33d32011-06-10 03:11:26 +000010330 if (!ActiveTemplateInstantiations.empty()) {
10331 // In a template instantiation, do not offer fix-its for tag mismatches
10332 // since they usually mess up the template instead of fixing the problem.
10333 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010334 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10335 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010336 return true;
10337 }
10338
10339 if (isDefinition) {
10340 // On definitions, check previous tags and issue a fix-it for each
10341 // one that doesn't match the current tag.
10342 if (Previous->getDefinition()) {
10343 // Don't suggest fix-its for redefinitions.
10344 return true;
10345 }
10346
10347 bool previousMismatch = false;
10348 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10349 E(Previous->redecls_end()); I != E; ++I) {
10350 if (I->getTagKind() != NewTag) {
10351 if (!previousMismatch) {
10352 previousMismatch = true;
10353 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010354 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10355 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010356 }
10357 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010358 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010359 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010360 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010361 }
10362 }
10363 return true;
10364 }
10365
10366 // Check for a previous definition. If current tag and definition
10367 // are same type, do nothing. If no definition, but disagree with
10368 // with previous tag type, give a warning, but no fix-it.
10369 const TagDecl *Redecl = Previous->getDefinition() ?
10370 Previous->getDefinition() : Previous;
10371 if (Redecl->getTagKind() == NewTag) {
10372 return true;
10373 }
10374
Douglas Gregord9034f02009-05-14 16:41:31 +000010375 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010376 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10377 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010378 Diag(Redecl->getLocation(), diag::note_previous_use);
10379
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010380 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010381 if (Previous->getDefinition()) {
10382 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010383 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010384 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010385 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010386 }
10387
Douglas Gregord9034f02009-05-14 16:41:31 +000010388 return true;
10389 }
10390 return false;
10391}
10392
Steve Naroff30d242c2007-09-15 18:49:24 +000010393/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010394/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010395/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010396/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +000010397Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010398 SourceLocation KWLoc, CXXScopeSpec &SS,
10399 IdentifierInfo *Name, SourceLocation NameLoc,
10400 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010401 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010402 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010403 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010404 SourceLocation ScopedEnumKWLoc,
10405 bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010406 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010407 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010408 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010409 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010410 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010411 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010412
Douglas Gregord6ab8742009-05-28 23:31:59 +000010413 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010414 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010415 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010416
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010417 // FIXME: Check explicit specializations more carefully.
10418 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010419 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010420
10421 // We only need to do this matching if we have template parameters
10422 // or a scope specifier, which also conveniently avoids this work
10423 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010424 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010425 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010426 if (TemplateParameterList *TemplateParams =
10427 MatchTemplateParametersToScopeSpecifier(
10428 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10429 isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010430 if (Kind == TTK_Enum) {
10431 Diag(KWLoc, diag::err_enum_template);
10432 return 0;
10433 }
10434
Douglas Gregor3dad8422009-09-26 06:47:28 +000010435 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010436 // This is a declaration or definition of a class template (which may
10437 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010438
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010439 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010440 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010441
Douglas Gregore93e46c2009-07-22 23:48:44 +000010442 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010443 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010444 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010445 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010446 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010447 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010448 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010449 return Result.get();
10450 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010451 // The "template<>" header is extraneous.
10452 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010453 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010454 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010455 }
Mike Stump11289f42009-09-09 15:08:12 +000010456 }
10457 }
10458
Douglas Gregor0bf31402010-10-08 23:50:27 +000010459 // Figure out the underlying type if this a enum declaration. We need to do
10460 // this early, because it's needed to detect if this is an incompatible
10461 // redeclaration.
10462 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10463
10464 if (Kind == TTK_Enum) {
10465 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10466 // No underlying type explicitly specified, or we failed to parse the
10467 // type, default to int.
10468 EnumUnderlying = Context.IntTy.getTypePtr();
10469 else if (UnderlyingType.get()) {
10470 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10471 // integral type; any cv-qualification is ignored.
10472 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010473 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010474 EnumUnderlying = TI;
10475
Richard Smith4b38ded2012-03-14 23:13:10 +000010476 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010477 // Recover by falling back to int.
10478 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010479
Richard Smith4b38ded2012-03-14 23:13:10 +000010480 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010481 UPPC_FixedUnderlyingType))
10482 EnumUnderlying = Context.IntTy.getTypePtr();
10483
David Blaikiebbafb8a2012-03-11 07:00:24 +000010484 } else if (getLangOpts().MicrosoftMode)
Francois Picheta3108062010-10-18 15:01:13 +000010485 // Microsoft enums are always of int type.
10486 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010487 }
10488
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010489 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010490 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010491 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010492
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010493 RedeclarationKind Redecl = ForRedeclaration;
10494 if (TUK == TUK_Friend || TUK == TUK_Reference)
10495 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010496
10497 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010498 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010499 if (Name && SS.isNotEmpty()) {
10500 // We have a nested-name tag ('struct foo::bar').
10501
10502 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010503 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010504 Name = 0;
10505 goto CreateNewDecl;
10506 }
10507
John McCall7f41d982009-09-11 04:59:25 +000010508 // If this is a friend or a reference to a class in a dependent
10509 // context, don't try to make a decl for it.
10510 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10511 DC = computeDeclContext(SS, false);
10512 if (!DC) {
10513 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010514 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010515 }
John McCall0b66eb32010-05-01 00:40:08 +000010516 } else {
10517 DC = computeDeclContext(SS, true);
10518 if (!DC) {
10519 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10520 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010521 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010522 }
John McCall7f41d982009-09-11 04:59:25 +000010523 }
10524
John McCall0b66eb32010-05-01 00:40:08 +000010525 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010526 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010527
Douglas Gregor8761da52009-02-03 00:34:39 +000010528 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010529 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010530 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010531
John McCall1f82f242009-11-18 22:49:29 +000010532 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010533 return 0;
John McCall6538c932009-10-10 05:48:19 +000010534
John McCall1f82f242009-11-18 22:49:29 +000010535 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010536 // Name lookup did not find anything. However, if the
10537 // nested-name-specifier refers to the current instantiation,
10538 // and that current instantiation has any dependent base
10539 // classes, we might find something at instantiation time: treat
10540 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010541 // But this only makes any sense for reference-like lookups.
10542 if (Previous.wasNotFoundInCurrentInstantiation() &&
10543 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010544 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010545 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010546 }
10547
10548 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010549 Diag(NameLoc, diag::err_not_tag_in_scope)
10550 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010551 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010552 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010553 goto CreateNewDecl;
10554 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010555 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010556 // If this is a named struct, check to see if there was a previous forward
10557 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010558 // FIXME: We're looking into outer scopes here, even when we
10559 // shouldn't be. Doing so can result in ambiguities that we
10560 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010561 LookupName(Previous, S);
10562
John McCall3c581bf2013-03-20 01:53:00 +000010563 // When declaring or defining a tag, ignore ambiguities introduced
10564 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010565 if (Previous.isAmbiguous() &&
10566 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010567 LookupResult::Filter F = Previous.makeFilter();
10568 while (F.hasNext()) {
10569 NamedDecl *ND = F.next();
10570 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10571 F.erase();
10572 }
10573 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010574 }
John McCall3c581bf2013-03-20 01:53:00 +000010575
10576 // C++11 [namespace.memdef]p3:
10577 // If the name in a friend declaration is neither qualified nor
10578 // a template-id and the declaration is a function or an
10579 // elaborated-type-specifier, the lookup to determine whether
10580 // the entity has been previously declared shall not consider
10581 // any scopes outside the innermost enclosing namespace.
10582 //
10583 // Does it matter that this should be by scope instead of by
10584 // semantic context?
10585 if (!Previous.empty() && TUK == TUK_Friend) {
10586 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10587 LookupResult::Filter F = Previous.makeFilter();
10588 while (F.hasNext()) {
10589 NamedDecl *ND = F.next();
10590 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010591 if (DC->isFileContext() &&
10592 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010593 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010594 FriendSawTagOutsideEnclosingNamespace = true;
10595 }
John McCall3c581bf2013-03-20 01:53:00 +000010596 }
10597 F.done();
10598 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010599
John McCall1f82f242009-11-18 22:49:29 +000010600 // Note: there used to be some attempt at recovery here.
10601 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010602 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010603
David Blaikiebbafb8a2012-03-11 07:00:24 +000010604 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010605 // FIXME: This makes sure that we ignore the contexts associated
10606 // with C structs, unions, and enums when looking for a matching
10607 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010608 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010609 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10610 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010611 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010612 } else if (S->isFunctionPrototypeScope()) {
10613 // If this is an enum declaration in function prototype scope, set its
10614 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010615 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010616 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010617 }
10618
John McCall1f82f242009-11-18 22:49:29 +000010619 if (Previous.isSingleResult() &&
10620 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010621 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010622 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010623 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010624 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010625 }
10626
David Blaikiebbafb8a2012-03-11 07:00:24 +000010627 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010628 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010629 // This is a declaration of or a reference to "std::bad_alloc".
10630 isStdBadAlloc = true;
10631
John McCall1f82f242009-11-18 22:49:29 +000010632 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010633 // std::bad_alloc has been implicitly declared (but made invisible to
10634 // name lookup). Fill in this implicit declaration as the previous
10635 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010636 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010637 }
10638 }
John McCall1f82f242009-11-18 22:49:29 +000010639
John McCalle9eaf8e2010-03-25 21:28:06 +000010640 // If we didn't find a previous declaration, and this is a reference
10641 // (or friend reference), move to the correct scope. In C++, we
10642 // also need to do a redeclaration lookup there, just in case
10643 // there's a shadow friend decl.
10644 if (Name && Previous.empty() &&
10645 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10646 if (Invalid) goto CreateNewDecl;
10647 assert(SS.isEmpty());
10648
10649 if (TUK == TUK_Reference) {
10650 // C++ [basic.scope.pdecl]p5:
10651 // -- for an elaborated-type-specifier of the form
10652 //
10653 // class-key identifier
10654 //
10655 // if the elaborated-type-specifier is used in the
10656 // decl-specifier-seq or parameter-declaration-clause of a
10657 // function defined in namespace scope, the identifier is
10658 // declared as a class-name in the namespace that contains
10659 // the declaration; otherwise, except as a friend
10660 // declaration, the identifier is declared in the smallest
10661 // non-class, non-function-prototype scope that contains the
10662 // declaration.
10663 //
10664 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10665 // C structs and unions.
10666 //
10667 // It is an error in C++ to declare (rather than define) an enum
10668 // type, including via an elaborated type specifier. We'll
10669 // diagnose that later; for now, declare the enum in the same
10670 // scope as we would have picked for any other tag type.
10671 //
10672 // GNU C also supports this behavior as part of its incomplete
10673 // enum types extension, while GNU C++ does not.
10674 //
10675 // Find the context where we'll be declaring the tag.
10676 // FIXME: We would like to maintain the current DeclContext as the
10677 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010678 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010679 SearchDC = SearchDC->getParent();
10680
10681 // Find the scope where we'll be declaring the tag.
10682 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010683 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010684 S->isFunctionPrototypeScope()) ||
10685 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010686 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010687 S = S->getParent();
10688 } else {
10689 assert(TUK == TUK_Friend);
10690 // C++ [namespace.memdef]p3:
10691 // If a friend declaration in a non-local class first declares a
10692 // class or function, the friend class or function is a member of
10693 // the innermost enclosing namespace.
10694 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010695 }
10696
John McCalle87beb22010-04-23 18:46:30 +000010697 // In C++, we need to do a redeclaration lookup to properly
10698 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010699 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010700 Previous.setRedeclarationKind(ForRedeclaration);
10701 LookupQualifiedName(Previous, SearchDC);
10702 }
10703 }
10704
John McCall1f82f242009-11-18 22:49:29 +000010705 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +000010706 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +000010707
10708 // It's okay to have a tag decl in the same scope as a typedef
10709 // which hides a tag decl in the same scope. Finding this
10710 // insanity with a redeclaration lookup can only actually happen
10711 // in C++.
10712 //
10713 // This is also okay for elaborated-type-specifiers, which is
10714 // technically forbidden by the current standard but which is
10715 // okay according to the likely resolution of an open issue;
10716 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010717 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010718 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010719 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10720 TagDecl *Tag = TT->getDecl();
10721 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010722 Tag->getDeclContext()->getRedeclContext()
10723 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010724 PrevDecl = Tag;
10725 Previous.clear();
10726 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010727 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010728 }
10729 }
10730 }
10731 }
10732
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010733 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010734 // If this is a use of a previous tag, or if the tag is already declared
10735 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010736 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010737 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Richard Smith72bcaec2013-12-05 04:30:04 +000010738 isDeclInScope(PrevDecl, SearchDC, S,
10739 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010740 // Make sure that this wasn't declared as an enum and now used as a
10741 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010742 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10743 TUK == TUK_Definition, KWLoc,
10744 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010745 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010746 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10747 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010748 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010749 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010750 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010751 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10752 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010753 else
10754 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010755 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010756
Mike Stump11289f42009-09-09 15:08:12 +000010757 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010758 Kind = PrevTagDecl->getTagKind();
10759 else {
10760 // Recover by making this an anonymous redefinition.
10761 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010762 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010763 Invalid = true;
10764 }
10765 }
10766
Douglas Gregor0bf31402010-10-08 23:50:27 +000010767 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10768 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10769
Richard Smith0f8ee222012-01-10 01:33:14 +000010770 // If this is an elaborated-type-specifier for a scoped enumeration,
10771 // the 'class' keyword is not necessary and not permitted.
10772 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10773 if (ScopedEnum)
10774 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10775 << PrevEnum->isScoped()
10776 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10777 return PrevTagDecl;
10778 }
10779
Richard Smith4b38ded2012-03-14 23:13:10 +000010780 QualType EnumUnderlyingTy;
10781 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10782 EnumUnderlyingTy = TI->getType();
10783 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10784 EnumUnderlyingTy = QualType(T, 0);
10785
Douglas Gregor0bf31402010-10-08 23:50:27 +000010786 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010787 // returning the previous declaration, unless this is a definition,
10788 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010789 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10790 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010791 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010792 }
10793
David Majnemer55890bf2013-06-11 03:51:23 +000010794 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010795 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010796 // except that a nested class or member class template can be declared
10797 // and then later defined.
10798 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10799 S->isDeclScope(PrevDecl)) {
10800 Diag(NameLoc, diag::ext_member_redeclared);
10801 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10802 }
10803
Douglas Gregor170512f2009-04-01 23:51:29 +000010804 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010805 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010806
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010807 // FIXME: In the future, return a variant or some other clue
10808 // for the consumer of this Decl to know it doesn't own it.
10809 // For our current ASTs this shouldn't be a problem, but will
10810 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010811 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010812 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010813 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010814
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010815 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010816 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010817 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010818 // If we're defining a specialization and the previous definition
10819 // is from an implicit instantiation, don't emit an error
10820 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010821 bool IsExplicitSpecializationAfterInstantiation = false;
10822 if (isExplicitSpecialization) {
10823 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10824 IsExplicitSpecializationAfterInstantiation =
10825 RD->getTemplateSpecializationKind() !=
10826 TSK_ExplicitSpecialization;
10827 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10828 IsExplicitSpecializationAfterInstantiation =
10829 ED->getTemplateSpecializationKind() !=
10830 TSK_ExplicitSpecialization;
10831 }
10832
10833 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010834 // A redeclaration in function prototype scope in C isn't
10835 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010836 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010837 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10838 else
10839 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010840 Diag(Def->getLocation(), diag::note_previous_definition);
10841 // If this is a redefinition, recover by making this
10842 // struct be anonymous, which will make any later
10843 // references get the previous definition.
10844 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010845 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010846 Invalid = true;
10847 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010848 } else {
10849 // If the type is currently being defined, complain
10850 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010851 const TagType *Tag
10852 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010853 if (Tag->isBeingDefined()) {
10854 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010855 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010856 diag::note_previous_definition);
10857 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010858 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010859 Invalid = true;
10860 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010861 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010862
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010863 // Okay, this is definition of a previously declared or referenced
10864 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010865 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010866 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010867 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000010868 // have a definition. Just create a new decl.
10869
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010870 } else {
10871 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000010872 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010873 // new decl/type. We set PrevDecl to NULL so that the entities
10874 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000010875 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000010876 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010877 // If we get here, we're going to create a new Decl. If PrevDecl
10878 // is non-NULL, it's a definition of the tag declared by
10879 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000010880
10881
10882 // Otherwise, PrevDecl is not a tag, but was found with tag
10883 // lookup. This is only actually possible in C++, where a few
10884 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010885 } else {
John McCalle87beb22010-04-23 18:46:30 +000010886 // Use a better diagnostic if an elaborated-type-specifier
10887 // found the wrong kind of type on the first
10888 // (non-redeclaration) lookup.
10889 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10890 !Previous.isForRedeclaration()) {
10891 unsigned Kind = 0;
10892 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010893 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10894 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010895 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10896 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10897 Invalid = true;
10898
10899 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000010900 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10901 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000010902 // do nothing
10903
10904 // Diagnose implicit declarations introduced by elaborated types.
10905 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10906 unsigned Kind = 0;
10907 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010908 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10909 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010910 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10911 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10912 Invalid = true;
10913
10914 // Otherwise it's a declaration. Call out a particularly common
10915 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000010916 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10917 unsigned Kind = 0;
10918 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000010919 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000010920 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000010921 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10922 Invalid = true;
10923
10924 // Otherwise, diagnose.
10925 } else {
10926 // The tag name clashes with something else in the target scope,
10927 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010928 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000010929 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010930 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000010931 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010932 }
John McCalle87beb22010-04-23 18:46:30 +000010933
10934 // The existing declaration isn't relevant to us; we're in a
10935 // new scope, so clear out the previous declaration.
10936 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000010937 }
Chris Lattner18b19622007-01-22 07:39:13 +000010938 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000010939
Chris Lattner438e5012008-12-17 07:13:27 +000010940CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000010941
John McCall1f82f242009-11-18 22:49:29 +000010942 TagDecl *PrevDecl = 0;
10943 if (Previous.isSingleResult())
10944 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10945
Chris Lattnerbf0b7982007-01-23 04:27:41 +000010946 // If there is an identifier, use the location of the identifier as the
10947 // location of the decl, otherwise use the location of the struct/union
10948 // keyword.
10949 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000010950
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010951 // Otherwise, create a new declaration. If there is a previous
10952 // declaration of the same entity, the two will be linked via
10953 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000010954 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000010955
Douglas Gregor0bf31402010-10-08 23:50:27 +000010956 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010957 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000010958 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10959 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010960 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010961 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010962 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000010963 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010964 if (TUK != TUK_Definition && !Invalid) {
10965 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000010966 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10967 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010968 // C++0x: 7.2p2: opaque-enum-declaration.
10969 // Conflicts are diagnosed above. Do nothing.
10970 }
10971 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010972 Diag(Loc, diag::ext_forward_ref_enum_def)
10973 << New;
10974 Diag(Def->getLocation(), diag::note_previous_definition);
10975 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000010976 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010977 if (getLangOpts().MicrosoftMode)
Francois Pichet488b4a72010-09-12 05:06:55 +000010978 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010979 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000010980 DiagID = diag::err_forward_ref_enum;
10981 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010982
10983 // If this is a forward-declared reference to an enumeration, make a
10984 // note of it; we won't actually be introducing the declaration into
10985 // the declaration context.
10986 if (TUK == TUK_Reference)
10987 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010988 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000010989 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000010990
10991 if (EnumUnderlying) {
10992 EnumDecl *ED = cast<EnumDecl>(New);
10993 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10994 ED->setIntegerTypeSourceInfo(TI);
10995 else
10996 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10997 ED->setPromotionType(ED->getIntegerType());
10998 }
10999
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011000 } else {
11001 // struct/union/class
11002
Chris Lattner776fac82007-06-09 00:53:06 +000011003 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11004 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011005 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000011006 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011007 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011008 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011009
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000011010 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000011011 StdBadAlloc = cast<CXXRecordDecl>(New);
11012 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011013 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011014 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000011015 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011016
John McCall3e11ebe2010-03-15 10:12:16 +000011017 // Maybe add qualifier info.
11018 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011019 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011020 // If this is either a declaration or a definition, check the
11021 // nested-name-specifier against the current context. We don't do this
11022 // for explicit specializations, because they have similar checking
11023 // (with more specific diagnostics) in the call to
11024 // CheckMemberSpecialization, below.
11025 if (!isExplicitSpecialization &&
11026 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11027 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11028 Invalid = true;
11029
Douglas Gregor14454802011-02-25 02:25:35 +000011030 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000011031 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000011032 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000011033 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011034 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000011035 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011036 }
11037 else
11038 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011039 }
11040
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011041 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11042 // Add alignment attributes if necessary; these attributes are checked when
11043 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011044 //
11045 // It is important for implementing the correct semantics that this
11046 // happen here (in act on tag decl). The #pragma pack stack is
11047 // maintained as a result of parser callbacks which can occur at
11048 // many points during the parsing of a struct declaration (because
11049 // the #pragma tokens are effectively skipped over during the
11050 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011051 if (TUK == TUK_Definition) {
11052 AddAlignmentAttributesForRecord(RD);
11053 AddMsStructLayoutForRecord(RD);
11054 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011055 }
11056
Douglas Gregor21823bf2011-12-20 18:11:52 +000011057 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011058 if (isExplicitSpecialization)
11059 Diag(New->getLocation(), diag::err_module_private_specialization)
11060 << 2
11061 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011062 // __module_private__ does not apply to local classes. However, we only
11063 // diagnose this as an error when the declaration specifiers are
11064 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011065 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011066 New->setModulePrivate();
11067 }
11068
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011069 // If this is a specialization of a member class (of a class template),
11070 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011071 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011072 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011073
Douglas Gregordee1be82009-01-17 00:42:38 +000011074 if (Invalid)
11075 New->setInvalidDecl();
11076
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011077 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011078 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011079
Douglas Gregordee1be82009-01-17 00:42:38 +000011080 // If we're declaring or defining a tag in function prototype scope
11081 // in C, note that this type can only be used within the function.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011082 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor658b9552009-01-09 22:42:13 +000011083 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11084
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011085 // Set the lexical context. If the tag has a C++ scope specifier, the
11086 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011087 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011088
John McCallaa74a0c2009-08-28 07:59:38 +000011089 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011090 // In Microsoft mode, a friend declaration also acts as a forward
11091 // declaration so we always pass true to setObjectOfFriendDecl to make
11092 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011093 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011094 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11095 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011096
Anders Carlsson5558ca12009-03-26 01:19:02 +000011097 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011098 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011099 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011100
John McCall9bb74a52009-07-31 02:45:11 +000011101 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011102 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011103
Chris Lattner18b19622007-01-22 07:39:13 +000011104 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011105 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011106 // We might be replacing an existing declaration in the lookup tables;
11107 // if so, borrow its access specifier.
11108 if (PrevDecl)
11109 New->setAccess(PrevDecl->getAccess());
11110
Sebastian Redl50c68252010-08-31 00:36:30 +000011111 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011112 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011113 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011114 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11115 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011116 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011117 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011118 PushOnScopeChains(New, S, !IsForwardReference);
11119 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011120 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011121
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011122 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011123 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011124 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011125
Douglas Gregor27821ce2009-07-07 16:35:42 +000011126 // If this is the C FILE type, notify the AST context.
11127 if (IdentifierInfo *II = New->getIdentifier())
11128 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011129 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011130 II->isStr("FILE"))
11131 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011132
James Molloy6f8780b2012-02-29 10:24:19 +000011133 // If we were in function prototype scope (and not in C++ mode), add this
11134 // tag to the list of decls to inject into the function definition scope.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011135 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy6f8780b2012-02-29 10:24:19 +000011136 InFunctionDeclarator && Name)
11137 DeclsInPrototypeScope.push_back(New);
11138
Rafael Espindolac67f2232012-05-10 02:50:16 +000011139 if (PrevDecl)
11140 mergeDeclAttributes(New, PrevDecl);
11141
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011142 // If there's a #pragma GCC visibility in scope, set the visibility of this
11143 // record.
11144 AddPushedVisibilityAttribute(New);
11145
Douglas Gregord6ab8742009-05-28 23:31:59 +000011146 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011147 // In C++, don't return an invalid declaration. We can't recover well from
11148 // the cases where we make the type anonymous.
11149 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011150}
Chris Lattner1300fb92007-01-23 23:42:53 +000011151
John McCall48871652010-08-21 09:40:31 +000011152void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011153 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011154 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011155
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011156 // Enter the tag context.
11157 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011158
11159 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011160
11161 // If there's a #pragma GCC visibility in scope, set the visibility of this
11162 // record.
11163 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011164}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011165
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011166Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011167 assert(isa<ObjCContainerDecl>(IDecl) &&
11168 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11169 DeclContext *OCD = cast<DeclContext>(IDecl);
11170 assert(getContainingDC(OCD) == CurContext &&
11171 "The next DeclContext should be lexically contained in the current one.");
11172 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011173 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011174}
11175
John McCall48871652010-08-21 09:40:31 +000011176void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011177 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011178 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011179 SourceLocation LBraceLoc) {
11180 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011181 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011182
John McCall1c7e6ec2009-12-20 07:58:13 +000011183 FieldCollector->StartClass();
11184
11185 if (!Record->getIdentifier())
11186 return;
11187
Anders Carlsson30f29442011-03-25 14:31:08 +000011188 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011189 Record->addAttr(new (Context)
11190 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11191
John McCall1c7e6ec2009-12-20 07:58:13 +000011192 // C++ [class]p2:
11193 // [...] The class-name is also inserted into the scope of the
11194 // class itself; this is known as the injected-class-name. For
11195 // purposes of access checking, the injected-class-name is treated
11196 // as if it were a public member name.
11197 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011198 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11199 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011200 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011201 /*PrevDecl=*/0,
11202 /*DelayTypeCreation=*/true);
11203 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011204 InjectedClassName->setImplicit();
11205 InjectedClassName->setAccess(AS_public);
11206 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11207 InjectedClassName->setDescribedClassTemplate(Template);
11208 PushOnScopeChains(InjectedClassName, S);
11209 assert(InjectedClassName->isInjectedClassName() &&
11210 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011211}
11212
John McCall48871652010-08-21 09:40:31 +000011213void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011214 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011215 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011216 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011217 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011218
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011219 // Make sure we "complete" the definition even it is invalid.
11220 if (Tag->isBeingDefined()) {
11221 assert(Tag->isInvalidDecl() && "We should already have completed it");
11222 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11223 RD->completeDefinition();
11224 }
11225
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011226 if (isa<CXXRecordDecl>(Tag))
11227 FieldCollector->FinishClass();
11228
11229 // Exit this scope of this tag's definition.
11230 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011231
11232 if (getCurLexicalContext()->isObjCContainer() &&
11233 Tag->getDeclContext()->isFileContext())
11234 Tag->setTopLevelDeclInObjCContainer();
11235
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011236 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011237 if (!Tag->isInvalidDecl())
11238 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011239}
Chris Lattner535b8302008-06-21 19:39:06 +000011240
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011241void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011242 // Exit this scope of this interface definition.
11243 PopDeclContext();
11244}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011245
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011246void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011247 assert(DC == CurContext && "Mismatch of container contexts");
11248 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011249 ActOnObjCContainerFinishDefinition();
11250}
11251
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011252void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11253 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011254 OriginalLexicalContext = 0;
11255}
11256
John McCall48871652010-08-21 09:40:31 +000011257void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011258 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011259 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011260 Tag->setInvalidDecl();
11261
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011262 // Make sure we "complete" the definition even it is invalid.
11263 if (Tag->isBeingDefined()) {
11264 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11265 RD->completeDefinition();
11266 }
11267
John McCall71ba5f22010-03-17 19:25:57 +000011268 // We're undoing ActOnTagStartDefinition here, not
11269 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11270 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011271
11272 PopDeclContext();
11273}
11274
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011275// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011276ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11277 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011278 QualType FieldTy, bool IsMsStruct,
11279 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011280 // Default to true; that shouldn't confuse checks for emptiness
11281 if (ZeroWidth)
11282 *ZeroWidth = true;
11283
Chris Lattner73bf7b42009-03-05 22:45:59 +000011284 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011285 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011286 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011287 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011288 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011289 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011290 if (FieldName)
11291 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11292 << FieldName << FieldTy << BitWidth->getSourceRange();
11293 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11294 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011295 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11296 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011297 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011298
11299 // If the bit-width is type- or value-dependent, don't try to check
11300 // it now.
11301 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011302 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011303
Anders Carlsson5df391e2008-12-06 20:33:04 +000011304 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011305 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11306 if (ICE.isInvalid())
11307 return ICE;
11308 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011309
Eli Friedmanc96d4962009-08-15 21:55:26 +000011310 if (Value != 0 && ZeroWidth)
11311 *ZeroWidth = false;
11312
Chris Lattner81ed6802008-12-12 04:56:04 +000011313 // Zero-width bitfield is ok for anonymous field.
11314 if (Value == 0 && FieldName)
11315 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011316
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011317 if (Value.isSigned() && Value.isNegative()) {
11318 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011319 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011320 << FieldName << Value.toString(10);
11321 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11322 << Value.toString(10);
11323 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011324
Douglas Gregor1efa4372009-03-11 18:59:21 +000011325 if (!FieldTy->isDependentType()) {
11326 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011327 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011328 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11329 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011330 if (FieldName)
11331 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11332 << FieldName << (unsigned)Value.getZExtValue()
11333 << (unsigned)TypeSize;
11334
11335 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11336 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11337 }
11338
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011339 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011340 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11341 << FieldName << (unsigned)Value.getZExtValue()
11342 << (unsigned)TypeSize;
11343 else
11344 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11345 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011346 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011347 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011348
Richard Smithf4c51d92012-02-04 09:53:13 +000011349 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011350}
11351
Richard Smith938f40b2011-06-11 17:19:42 +000011352/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011353/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011354Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011355 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011356 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011357 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011358 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011359 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011360}
11361
11362/// HandleField - Analyze a field of a C struct or a C++ data member.
11363///
11364FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11365 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011366 Declarator &D, Expr *BitWidth,
11367 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011368 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011369 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011370 SourceLocation Loc = DeclStart;
11371 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011372
John McCall8cb7bdf2010-06-04 23:28:52 +000011373 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11374 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011375 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011376 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011377
Douglas Gregora02a72a2010-12-15 23:18:36 +000011378 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11379 UPPC_DataMemberType)) {
11380 D.setInvalidType();
11381 T = Context.IntTy;
11382 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11383 }
11384 }
11385
Matt Arsenault376f7202013-02-26 21:16:00 +000011386 // TR 18037 does not allow fields to be declared with address spaces.
11387 if (T.getQualifiers().hasAddressSpace()) {
11388 Diag(Loc, diag::err_field_with_address_space);
11389 D.setInvalidType();
11390 }
11391
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011392 // OpenCL 1.2 spec, s6.9 r:
11393 // The event type cannot be used to declare a structure or union field.
11394 if (LangOpts.OpenCL && T->isEventT()) {
11395 Diag(Loc, diag::err_event_t_struct_field);
11396 D.setInvalidType();
11397 }
11398
Richard Smithb1402ae2013-03-18 22:52:47 +000011399 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011400
Richard Smithb4a9e862013-04-12 22:46:28 +000011401 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11402 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11403 diag::err_invalid_thread)
11404 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011405
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011406 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011407 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011408 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11409 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011410 switch (Previous.getResultKind()) {
11411 case LookupResult::Found:
11412 case LookupResult::FoundUnresolvedValue:
11413 PrevDecl = Previous.getAsSingle<NamedDecl>();
11414 break;
11415
11416 case LookupResult::FoundOverloaded:
11417 PrevDecl = Previous.getRepresentativeDecl();
11418 break;
11419
11420 case LookupResult::NotFound:
11421 case LookupResult::NotFoundInCurrentInstantiation:
11422 case LookupResult::Ambiguous:
11423 break;
11424 }
11425 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011426
11427 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11428 // Maybe we will complain about the shadowed template parameter.
11429 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11430 // Just pretend that we didn't see the previous declaration.
11431 PrevDecl = 0;
11432 }
11433
Douglas Gregor1efa4372009-03-11 18:59:21 +000011434 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11435 PrevDecl = 0;
11436
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011437 bool Mutable
11438 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011439 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011440 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011441 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011442 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011443
11444 if (NewFD->isInvalidDecl())
11445 Record->setInvalidDecl();
11446
Douglas Gregor3baa6702011-09-12 16:11:24 +000011447 if (D.getDeclSpec().isModulePrivateSpecified())
11448 NewFD->setModulePrivate();
11449
Douglas Gregor1efa4372009-03-11 18:59:21 +000011450 if (NewFD->isInvalidDecl() && PrevDecl) {
11451 // Don't introduce NewFD into scope; there's already something
11452 // with the same name in the same scope.
11453 } else if (II) {
11454 PushOnScopeChains(NewFD, S);
11455 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011456 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011457
11458 return NewFD;
11459}
11460
11461/// \brief Build a new FieldDecl and check its well-formedness.
11462///
11463/// This routine builds a new FieldDecl given the fields name, type,
11464/// record, etc. \p PrevDecl should refer to any previous declaration
11465/// with the same name and in the same scope as the field to be
11466/// created.
11467///
11468/// \returns a new FieldDecl.
11469///
Mike Stump11289f42009-09-09 15:08:12 +000011470/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011471FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011472 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011473 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011474 bool Mutable, Expr *BitWidth,
11475 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011476 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011477 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011478 Declarator *D) {
11479 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011480 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011481 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011482
Douglas Gregor1efa4372009-03-11 18:59:21 +000011483 // If we receive a broken type, recover by assuming 'int' and
11484 // marking this declaration as invalid.
11485 if (T.isNull()) {
11486 InvalidDecl = true;
11487 T = Context.IntTy;
11488 }
11489
Eli Friedmand0e8de22009-12-07 00:22:08 +000011490 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011491 if (!EltTy->isDependentType()) {
11492 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11493 // Fields of incomplete type force their record to be invalid.
11494 Record->setInvalidDecl();
11495 InvalidDecl = true;
11496 } else {
11497 NamedDecl *Def;
11498 EltTy->isIncompleteType(&Def);
11499 if (Def && Def->isInvalidDecl()) {
11500 Record->setInvalidDecl();
11501 InvalidDecl = true;
11502 }
11503 }
John McCall2677e102010-08-16 23:42:35 +000011504 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011505
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011506 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11507 if (BitWidth && getLangOpts().OpenCL) {
11508 Diag(Loc, diag::err_opencl_bitfields);
11509 InvalidDecl = true;
11510 }
11511
Steve Naroff8eeeb132007-05-08 21:09:37 +000011512 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11513 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011514 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011515 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011516 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011517
11518 TypeSourceInfo *FixedTInfo =
11519 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11520 SizeIsNegative,
11521 Oversized);
11522 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011523 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011524 TInfo = FixedTInfo;
11525 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011526 } else {
11527 if (SizeIsNegative)
11528 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011529 else if (Oversized.getBoolValue())
11530 Diag(Loc, diag::err_array_too_large)
11531 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011532 else
11533 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011534 InvalidDecl = true;
11535 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011536 }
Mike Stump11289f42009-09-09 15:08:12 +000011537
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011538 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011539 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11540 diag::err_abstract_type_in_decl,
11541 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011542 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011543
Eli Friedmanc96d4962009-08-15 21:55:26 +000011544 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011545 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011546 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011547 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11548 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011549 if (!BitWidth) {
11550 InvalidDecl = true;
11551 BitWidth = 0;
11552 ZeroWidth = false;
11553 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011554 }
Mike Stump11289f42009-09-09 15:08:12 +000011555
John McCallb1cd7da2010-06-04 08:34:12 +000011556 // Check that 'mutable' is consistent with the type of the declaration.
11557 if (!InvalidDecl && Mutable) {
11558 unsigned DiagID = 0;
11559 if (T->isReferenceType())
11560 DiagID = diag::err_mutable_reference;
11561 else if (T.isConstQualified())
11562 DiagID = diag::err_mutable_const;
11563
11564 if (DiagID) {
11565 SourceLocation ErrLoc = Loc;
11566 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11567 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11568 Diag(ErrLoc, DiagID);
11569 Mutable = false;
11570 InvalidDecl = true;
11571 }
11572 }
11573
Richard Smithab44d5b2013-12-10 08:25:00 +000011574 // C++11 [class.union]p8 (DR1460):
11575 // At most one variant member of a union may have a
11576 // brace-or-equal-initializer.
11577 if (InitStyle != ICIS_NoInit)
11578 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11579
Abramo Bagnaradff19302011-03-08 08:55:46 +000011580 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011581 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011582 if (InvalidDecl)
11583 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011584
Douglas Gregor1efa4372009-03-11 18:59:21 +000011585 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11586 Diag(Loc, diag::err_duplicate_member) << II;
11587 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11588 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011589 }
11590
David Blaikiebbafb8a2012-03-11 07:00:24 +000011591 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011592 if (Record->isUnion()) {
11593 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11594 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11595 if (RDecl->getDefinition()) {
11596 // C++ [class.union]p1: An object of a class with a non-trivial
11597 // constructor, a non-trivial copy constructor, a non-trivial
11598 // destructor, or a non-trivial copy assignment operator
11599 // cannot be a member of a union, nor can an array of such
11600 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011601 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011602 NewFD->setInvalidDecl();
11603 }
11604 }
11605
11606 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011607 // the program is ill-formed, except when compiling with MSVC extensions
11608 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011609 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011610 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11611 diag::ext_union_member_of_reference_type :
11612 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011613 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011614 if (!getLangOpts().MicrosoftExt)
11615 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011616 }
11617 }
11618 }
11619
Douglas Gregor1efa4372009-03-11 18:59:21 +000011620 // FIXME: We need to pass in the attributes given an AST
11621 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011622 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011623 // FIXME: The current scope is almost... but not entirely... correct here.
11624 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011625
Richard Smith848e1f12013-02-01 08:12:08 +000011626 if (NewFD->hasAttrs())
11627 CheckAlignasUnderalignment(NewFD);
11628 }
11629
John McCall31168b02011-06-15 23:02:42 +000011630 // In auto-retain/release, infer strong retension for fields of
11631 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011632 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011633 NewFD->setInvalidDecl();
11634
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011635 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011636 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011637
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011638 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011639 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011640}
11641
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011642bool Sema::CheckNontrivialField(FieldDecl *FD) {
11643 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011644 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011645
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011646 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11647 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011648
11649 QualType EltTy = Context.getBaseElementType(FD->getType());
11650 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011651 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011652 if (RDecl->getDefinition()) {
11653 // We check for copy constructors before constructors
11654 // because otherwise we'll never get complaints about
11655 // copy constructors.
11656
11657 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011658 // We're required to check for any non-trivial constructors. Since the
11659 // implicit default constructor is suppressed if there are any
11660 // user-declared constructors, we just need to check that there is a
11661 // trivial default constructor and a trivial copy constructor. (We don't
11662 // worry about move constructors here, since this is a C++98 check.)
11663 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011664 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011665 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011666 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011667 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011668 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011669 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011670 member = CXXDestructor;
11671
11672 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011673 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011674 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011675 // Objective-C++ ARC: it is an error to have a non-trivial field of
11676 // a union. However, system headers in Objective-C programs
11677 // occasionally have Objective-C lifetime objects within unions,
11678 // and rather than cause the program to fail, we make those
11679 // members unavailable.
11680 SourceLocation Loc = FD->getLocation();
11681 if (getSourceManager().isInSystemHeader(Loc)) {
11682 if (!FD->hasAttr<UnavailableAttr>())
11683 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +000011684 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +000011685 return false;
11686 }
11687 }
Richard Smithf720df02011-10-19 20:41:51 +000011688
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011689 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011690 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11691 diag::err_illegal_union_or_anon_struct_member)
11692 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011693 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011694 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011695 }
11696 }
11697 }
Richard Smith92f241f2012-12-08 02:53:02 +000011698
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011699 return false;
11700}
11701
Mike Stump11289f42009-09-09 15:08:12 +000011702/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011703/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011704static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011705TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011706 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011707 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011708 case tok::objc_private: return ObjCIvarDecl::Private;
11709 case tok::objc_public: return ObjCIvarDecl::Public;
11710 case tok::objc_protected: return ObjCIvarDecl::Protected;
11711 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011712 }
11713}
11714
Mike Stump11289f42009-09-09 15:08:12 +000011715/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011716/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011717Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011718 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011719 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011720 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011721
Fariborz Jahaniande615832008-04-10 23:32:45 +000011722 IdentifierInfo *II = D.getIdentifier();
11723 Expr *BitWidth = (Expr*)BitfieldWidth;
11724 SourceLocation Loc = DeclStart;
11725 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011726
Fariborz Jahaniande615832008-04-10 23:32:45 +000011727 // FIXME: Unnamed fields can be handled in various different ways, for
11728 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011729
John McCall8cb7bdf2010-06-04 23:28:52 +000011730 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11731 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011732
Fariborz Jahaniande615832008-04-10 23:32:45 +000011733 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011734 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011735 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011736 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011737 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011738 } else {
11739 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011740
Fariborz Jahaniande615832008-04-10 23:32:45 +000011741 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011742
Fariborz Jahaniande615832008-04-10 23:32:45 +000011743 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011744 if (T->isReferenceType()) {
11745 Diag(Loc, diag::err_ivar_reference_type);
11746 D.setInvalidType();
11747 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011748 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11749 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011750 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011751 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011752 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011753 }
Mike Stump11289f42009-09-09 15:08:12 +000011754
Ted Kremenek73295fa2008-07-23 18:04:17 +000011755 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011756 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011757 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11758 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011759 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011760 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011761 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11762 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011763 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011764 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011765 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011766 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011767 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011768 EnclosingContext = IMPDecl->getClassInterface();
11769 assert(EnclosingContext && "Implementation has no class interface!");
11770 }
11771 else
11772 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011773 } else {
11774 if (ObjCCategoryDecl *CDecl =
11775 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011776 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011777 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011778 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011779 }
11780 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011781 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011782 }
Mike Stump11289f42009-09-09 15:08:12 +000011783
Ted Kremenek73295fa2008-07-23 18:04:17 +000011784 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011785 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11786 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011787 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011788
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011789 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011790 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011791 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011792 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011793 && !isa<TagDecl>(PrevDecl)) {
11794 Diag(Loc, diag::err_duplicate_member) << II;
11795 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11796 NewID->setInvalidDecl();
11797 }
11798 }
11799
Ted Kremenek73295fa2008-07-23 18:04:17 +000011800 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011801 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011802
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011803 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011804 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011805
John McCall31168b02011-06-15 23:02:42 +000011806 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011807 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011808 NewID->setInvalidDecl();
11809
Douglas Gregor3baa6702011-09-12 16:11:24 +000011810 if (D.getDeclSpec().isModulePrivateSpecified())
11811 NewID->setModulePrivate();
11812
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011813 if (II) {
11814 // FIXME: When interfaces are DeclContexts, we'll need to add
11815 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011816 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011817 IdResolver.AddDecl(NewID);
11818 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011819
John McCall5fb5df92012-06-20 06:18:46 +000011820 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011821 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011822 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011823
John McCall48871652010-08-21 09:40:31 +000011824 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011825}
11826
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011827/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011828/// class and class extensions. For every class \@interface and class
11829/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011830/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011831void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011832 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011833 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011834 return;
11835
11836 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11837 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11838
Richard Smithcaf33902011-10-10 18:28:20 +000011839 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011840 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011841 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011842 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011843 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011844 if (!CD->IsClassExtension())
11845 return;
11846 }
11847 // No need to add this to end of @implementation.
11848 else
11849 return;
11850 }
11851 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011852 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11853 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011854
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011855 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011856 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011857 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011858 Context.getTrivialTypeSourceInfo(Context.CharTy,
11859 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011860 ObjCIvarDecl::Private, BW,
11861 true);
11862 AllIvarDecls.push_back(Ivar);
11863}
11864
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011865void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11866 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11867 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000011868 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000011869
Eric Christopher7457aaf2012-07-19 22:22:51 +000011870 // If this is an Objective-C @implementation or category and we have
11871 // new fields here we should reset the layout of the interface since
11872 // it will now change.
11873 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11874 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11875 switch (DC->getKind()) {
11876 default: break;
11877 case Decl::ObjCCategory:
11878 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11879 break;
11880 case Decl::ObjCImplementation:
11881 Context.
11882 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11883 break;
11884 }
11885 }
11886
Eli Friedmana7679412012-02-07 05:00:47 +000011887 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11888
11889 // Start counting up the number of named members; make sure to include
11890 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000011891 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000011892 if (Record) {
11893 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11894 e = Record->decls_end(); i != e; i++) {
11895 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11896 if (IFD->getDeclName())
11897 ++NumNamedMembers;
11898 }
11899 }
11900
11901 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011902 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000011903
John McCall31168b02011-06-15 23:02:42 +000011904 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011905 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000011906 i != end; ++i) {
11907 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000011908
Chris Lattner720a0542007-01-25 00:44:24 +000011909 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000011910 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000011911
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011912 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000011913 // Remember all fields written by the user.
11914 RecFields.push_back(FD);
11915 }
Mike Stump11289f42009-09-09 15:08:12 +000011916
Chris Lattner73bf7b42009-03-05 22:45:59 +000011917 // If the field is already invalid for some reason, don't emit more
11918 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011919 if (FD->isInvalidDecl()) {
11920 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000011921 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000011922 }
Mike Stump11289f42009-09-09 15:08:12 +000011923
Douglas Gregorac1fb652009-03-24 19:52:54 +000011924 // C99 6.7.2.1p2:
11925 // A structure or union shall not contain a member with
11926 // incomplete or function type (hence, a structure shall not
11927 // contain an instance of itself, but may contain a pointer to
11928 // an instance of itself), except that the last member of a
11929 // structure with more than one named member may have incomplete
11930 // array type; such a structure (and any union containing,
11931 // possibly recursively, a member that is such a structure)
11932 // shall not be a member of a structure or an element of an
11933 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000011934 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011935 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000011936 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011937 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000011938 FD->setInvalidDecl();
11939 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000011940 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000011941 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000011942 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000011943 ((getLangOpts().MicrosoftExt ||
11944 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000011945 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011946 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000011947 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000011948 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000011949 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000011950 unsigned DiagID = 0;
11951 if (Record->isUnion())
11952 DiagID = getLangOpts().MicrosoftExt
11953 ? diag::ext_flexible_array_union_ms
11954 : getLangOpts().CPlusPlus
11955 ? diag::ext_flexible_array_union_gnu
11956 : diag::err_flexible_array_union;
11957 else if (Fields.size() == 1)
11958 DiagID = getLangOpts().MicrosoftExt
11959 ? diag::ext_flexible_array_empty_aggregate_ms
11960 : getLangOpts().CPlusPlus
11961 ? diag::ext_flexible_array_empty_aggregate_gnu
11962 : NumNamedMembers < 1
11963 ? diag::err_flexible_array_empty_aggregate
11964 : 0;
11965
11966 if (DiagID)
11967 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11968 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000011969 // While the layout of types that contain virtual bases is not specified
11970 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11971 // virtual bases after the derived members. This would make a flexible
11972 // array member declared at the end of an object not adjacent to the end
11973 // of the type.
11974 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11975 if (RD->getNumVBases() != 0)
11976 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11977 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000011978 if (!getLangOpts().C99)
11979 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11980 << FD->getDeclName() << Record->getTagKind();
11981
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011982 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +000011983 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011984 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000011985 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011986 FD->setInvalidDecl();
11987 EnclosingDecl->setInvalidDecl();
11988 continue;
11989 }
Chris Lattner720a0542007-01-25 00:44:24 +000011990 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000011991 if (Record)
11992 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000011993 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000011994 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000011995 diag::err_field_incomplete)) {
11996 // Incomplete type
11997 FD->setInvalidDecl();
11998 EnclosingDecl->setInvalidDecl();
11999 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012000 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000012001 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12002 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000012003 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000012004 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012005 } else {
12006 // If this is a struct/class and this is not the last element, reject
12007 // it. Note that GCC supports variable sized arrays in the middle of
12008 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000012009 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012010 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000012011 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012012 else {
12013 // We support flexible arrays at the end of structs in
12014 // other structs as an extension.
12015 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12016 << FD->getDeclName();
12017 if (Record)
12018 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012019 }
Chris Lattner720a0542007-01-25 00:44:24 +000012020 }
12021 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000012022 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12023 RequireNonAbstractType(FD->getLocation(), FD->getType(),
12024 diag::err_abstract_type_in_decl,
12025 AbstractIvarType)) {
12026 // Ivars can not have abstract class types
12027 FD->setInvalidDecl();
12028 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000012029 if (Record && FDTTy->getDecl()->hasObjectMember())
12030 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000012031 if (Record && FDTTy->getDecl()->hasVolatileMember())
12032 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012033 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012034 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012035 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12036 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12037 QualType T = Context.getObjCObjectPointerType(FD->getType());
12038 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012039 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12040 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12041 // It's an error in ARC if a field has lifetime.
12042 // We don't want to report this in a system header, though,
12043 // so we just make the field unavailable.
12044 // FIXME: that's really not sufficient; we need to make the type
12045 // itself invalid to, say, initialize or copy.
12046 QualType T = FD->getType();
12047 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12048 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12049 SourceLocation loc = FD->getLocation();
12050 if (getSourceManager().isInSystemHeader(loc)) {
12051 if (!FD->hasAttr<UnavailableAttr>()) {
12052 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
12053 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +000012054 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012055 } else {
12056 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012057 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012058 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012059 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012060 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012061 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012062 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012063 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012064 if (FD->getType()->isObjCObjectPointerType() ||
12065 FD->getType().isObjCGCStrong())
12066 Record->setHasObjectMember(true);
12067 else if (Context.getAsArrayType(FD->getType())) {
12068 QualType BaseType = Context.getBaseElementType(FD->getType());
12069 if (BaseType->isRecordType() &&
12070 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012071 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012072 else if (BaseType->isObjCObjectPointerType() ||
12073 BaseType.isObjCGCStrong())
12074 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012075 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012076 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012077 if (Record && FD->getType().isVolatileQualified())
12078 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012079 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012080 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012081 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012082 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012083
Chris Lattner82625602007-01-24 02:26:21 +000012084 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012085 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012086 bool Completed = false;
12087 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12088 if (!CXXRecord->isInvalidDecl()) {
12089 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012090 for (CXXRecordDecl::conversion_iterator
12091 I = CXXRecord->conversion_begin(),
12092 E = CXXRecord->conversion_end(); I != E; ++I)
12093 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012094
12095 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012096 if (CXXRecord->hasUserDeclaredDestructor()) {
12097 // Adjust user-defined destructor exception spec.
12098 if (getLangOpts().CPlusPlus11)
12099 AdjustDestructorExceptionSpec(CXXRecord,
12100 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012101 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012102
Douglas Gregor8fb95122010-09-29 00:15:42 +000012103 // Add any implicitly-declared members to this class.
12104 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12105
12106 // If we have virtual base classes, we may end up finding multiple
12107 // final overriders for a given virtual function. Check for this
12108 // problem now.
12109 if (CXXRecord->getNumVBases()) {
12110 CXXFinalOverriderMap FinalOverriders;
12111 CXXRecord->getFinalOverriders(FinalOverriders);
12112
12113 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12114 MEnd = FinalOverriders.end();
12115 M != MEnd; ++M) {
12116 for (OverridingMethods::iterator SO = M->second.begin(),
12117 SOEnd = M->second.end();
12118 SO != SOEnd; ++SO) {
12119 assert(SO->second.size() > 0 &&
12120 "Virtual function without overridding functions?");
12121 if (SO->second.size() == 1)
12122 continue;
12123
12124 // C++ [class.virtual]p2:
12125 // In a derived class, if a virtual member function of a base
12126 // class subobject has more than one final overrider the
12127 // program is ill-formed.
12128 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012129 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012130 Diag(M->first->getLocation(),
12131 diag::note_overridden_virtual_function);
12132 for (OverridingMethods::overriding_iterator
12133 OM = SO->second.begin(),
12134 OMEnd = SO->second.end();
12135 OM != OMEnd; ++OM)
12136 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012137 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012138
12139 Record->setInvalidDecl();
12140 }
12141 }
12142 CXXRecord->completeDefinition(&FinalOverriders);
12143 Completed = true;
12144 }
12145 }
12146 }
12147 }
12148
12149 if (!Completed)
12150 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012151
Richard Smith848e1f12013-02-01 08:12:08 +000012152 if (Record->hasAttrs())
12153 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012154
Serge Pavlov3cb80222013-11-14 02:13:03 +000012155 // Check if the structure/union declaration is a type that can have zero
12156 // size in C. For C this is a language extension, for C++ it may cause
12157 // compatibility problems.
12158 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012159 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012160 CheckForZeroSize = true;
12161 } else {
12162 // For C++ filter out types that cannot be referenced in C code.
12163 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12164 CheckForZeroSize =
12165 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12166 !CXXRecord->isDependentType() &&
12167 CXXRecord->isCLike();
12168 }
12169 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012170 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012171 bool IsEmpty = true;
12172 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012173 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012174 E = Record->field_end();
12175 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12176 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012177 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012178 if (I->getBitWidthValue(Context) > 0)
12179 ZeroSize = false;
12180 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012181 ++NonBitFields;
12182 QualType FieldType = I->getType();
12183 if (FieldType->isIncompleteType() ||
12184 !Context.getTypeSizeInChars(FieldType).isZero())
12185 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012186 }
12187 }
12188
Serge Pavlov3cb80222013-11-14 02:13:03 +000012189 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12190 // allowed in C++, but warn if its declaration is inside
12191 // extern "C" block.
12192 if (ZeroSize) {
12193 Diag(RecLoc, getLangOpts().CPlusPlus ?
12194 diag::warn_zero_size_struct_union_in_extern_c :
12195 diag::warn_zero_size_struct_union_compat)
12196 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12197 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012198
Serge Pavlov3cb80222013-11-14 02:13:03 +000012199 // Structs without named members are extension in C (C99 6.7.2.1p7),
12200 // but are accepted by GCC.
12201 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12202 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12203 diag::ext_no_named_members_in_struct_union)
12204 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012205 }
12206 }
Chris Lattner622c1932008-02-06 00:51:33 +000012207 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012208 ObjCIvarDecl **ClsFields =
12209 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012210 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012211 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012212 // Add ivar's to class's DeclContext.
12213 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12214 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012215 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012216 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012217 // Must enforce the rule that ivars in the base classes may not be
12218 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012219 if (ID->getSuperClass())
12220 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012221 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012222 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012223 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012224 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12225 // Ivar declared in @implementation never belongs to the implementation.
12226 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012227 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012228 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012229 IMPDecl->setIvarLBraceLoc(LBrac);
12230 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012231 } else if (ObjCCategoryDecl *CDecl =
12232 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012233 // case of ivars in class extension; all other cases have been
12234 // reported as errors elsewhere.
12235 // FIXME. Class extension does not have a LocEnd field.
12236 // CDecl->setLocEnd(RBrac);
12237 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012238 // Diagnose redeclaration of private ivars.
12239 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012240 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012241 if (IDecl) {
12242 if (const ObjCIvarDecl *ClsIvar =
12243 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12244 Diag(ClsFields[i]->getLocation(),
12245 diag::err_duplicate_ivar_declaration);
12246 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12247 continue;
12248 }
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012249 for (ObjCInterfaceDecl::known_extensions_iterator
12250 Ext = IDecl->known_extensions_begin(),
12251 ExtEnd = IDecl->known_extensions_end();
12252 Ext != ExtEnd; ++Ext) {
12253 if (const ObjCIvarDecl *ClsExtIvar
12254 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012255 Diag(ClsFields[i]->getLocation(),
12256 diag::err_duplicate_ivar_declaration);
12257 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12258 continue;
12259 }
12260 }
12261 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012262 ClsFields[i]->setLexicalDeclContext(CDecl);
12263 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012264 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012265 CDecl->setIvarLBraceLoc(LBrac);
12266 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012267 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012268 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012269
12270 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012271 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012272}
12273
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012274/// \brief Determine whether the given integral value is representable within
12275/// the given type T.
12276static bool isRepresentableIntegerValue(ASTContext &Context,
12277 llvm::APSInt &Value,
12278 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012279 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012280 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012281
Douglas Gregor0bf31402010-10-08 23:50:27 +000012282 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012283 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012284 --BitWidth;
12285 return Value.getActiveBits() <= BitWidth;
12286 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012287 return Value.getMinSignedBits() <= BitWidth;
12288}
12289
12290// \brief Given an integral type, return the next larger integral type
12291// (or a NULL type of no such type exists).
12292static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12293 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12294 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012295 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012296 const unsigned NumTypes = 4;
12297 QualType SignedIntegralTypes[NumTypes] = {
12298 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12299 };
12300 QualType UnsignedIntegralTypes[NumTypes] = {
12301 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12302 Context.UnsignedLongLongTy
12303 };
12304
12305 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012306 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12307 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012308 for (unsigned I = 0; I != NumTypes; ++I)
12309 if (Context.getTypeSize(Types[I]) > BitWidth)
12310 return Types[I];
12311
12312 return QualType();
12313}
12314
Douglas Gregor954f6b272009-03-17 19:05:46 +000012315EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12316 EnumConstantDecl *LastEnumConst,
12317 SourceLocation IdLoc,
12318 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012319 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012320 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012321 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012322 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012323
12324 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12325 Val = 0;
12326
Eli Friedman7c6515a2011-12-06 00:10:34 +000012327 if (Val)
12328 Val = DefaultLvalueConversion(Val).take();
12329
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012330 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012331 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012332 EltTy = Context.DependentTy;
12333 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012334 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012335 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012336 !getLangOpts().MicrosoftMode) {
Richard Smithf8379a02012-01-18 23:55:52 +000012337 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12338 // constant-expression in the enumerator-definition shall be a converted
12339 // constant expression of the underlying type.
12340 EltTy = Enum->getIntegerType();
12341 ExprResult Converted =
12342 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12343 CCEK_Enumerator);
12344 if (Converted.isInvalid())
12345 Val = 0;
12346 else
12347 Val = Converted.take();
12348 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012349 !(Val = VerifyIntegerConstantExpression(Val,
12350 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012351 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012352 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012353 if (Enum->isFixed()) {
12354 EltTy = Enum->getIntegerType();
12355
Richard Smithf8379a02012-01-18 23:55:52 +000012356 // In Obj-C and Microsoft mode, require the enumeration value to be
12357 // representable in the underlying type of the enumeration. In C++11,
12358 // we perform a non-narrowing conversion as part of converted constant
12359 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012360 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012361 if (getLangOpts().MicrosoftMode) {
Francois Picheta3108062010-10-18 15:01:13 +000012362 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012363 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012364 } else
12365 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012366 } else
John Wiegley01296292011-04-08 18:41:53 +000012367 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012368 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012369 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012370 // If the underlying type is not fixed, the type of each enumerator
12371 // is the type of its initializing value:
12372 // - If an initializer is specified for an enumerator, the
12373 // initializing value has the same type as the expression.
12374 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012375 } else {
12376 // C99 6.7.2.2p2:
12377 // The expression that defines the value of an enumeration constant
12378 // shall be an integer constant expression that has a value
12379 // representable as an int.
12380
12381 // Complain if the value is not representable in an int.
12382 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12383 Diag(IdLoc, diag::ext_enum_value_not_int)
12384 << EnumVal.toString(10) << Val->getSourceRange()
12385 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12386 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12387 // Force the type of the expression to 'int'.
12388 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12389 }
12390 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012391 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012392 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012393 }
12394 }
Mike Stump11289f42009-09-09 15:08:12 +000012395
Douglas Gregor954f6b272009-03-17 19:05:46 +000012396 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012397 if (Enum->isDependentType())
12398 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012399 else if (!LastEnumConst) {
12400 // C++0x [dcl.enum]p5:
12401 // If the underlying type is not fixed, the type of each enumerator
12402 // is the type of its initializing value:
12403 // - If no initializer is specified for the first enumerator, the
12404 // initializing value has an unspecified integral type.
12405 //
12406 // GCC uses 'int' for its unspecified integral type, as does
12407 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012408 if (Enum->isFixed()) {
12409 EltTy = Enum->getIntegerType();
12410 }
12411 else {
12412 EltTy = Context.IntTy;
12413 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012414 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012415 // Assign the last value + 1.
12416 EnumVal = LastEnumConst->getInitVal();
12417 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012418 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012419
12420 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012421 if (EnumVal < LastEnumConst->getInitVal()) {
12422 // C++0x [dcl.enum]p5:
12423 // If the underlying type is not fixed, the type of each enumerator
12424 // is the type of its initializing value:
12425 //
12426 // - Otherwise the type of the initializing value is the same as
12427 // the type of the initializing value of the preceding enumerator
12428 // unless the incremented value is not representable in that type,
12429 // in which case the type is an unspecified integral type
12430 // sufficient to contain the incremented value. If no such type
12431 // exists, the program is ill-formed.
12432 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012433 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012434 // There is no integral type larger enough to represent this
12435 // value. Complain, then allow the value to wrap around.
12436 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012437 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012438 ++EnumVal;
12439 if (Enum->isFixed())
12440 // When the underlying type is fixed, this is ill-formed.
12441 Diag(IdLoc, diag::err_enumerator_wrapped)
12442 << EnumVal.toString(10)
12443 << EltTy;
12444 else
12445 Diag(IdLoc, diag::warn_enumerator_too_large)
12446 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012447 } else {
12448 EltTy = T;
12449 }
12450
12451 // Retrieve the last enumerator's value, extent that type to the
12452 // type that is supposed to be large enough to represent the incremented
12453 // value, then increment.
12454 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012455 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012456 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012457 ++EnumVal;
12458
12459 // If we're not in C++, diagnose the overflow of enumerator values,
12460 // which in C99 means that the enumerator value is not representable in
12461 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12462 // permits enumerator values that are representable in some larger
12463 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012464 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012465 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012466 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012467 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12468 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12469 Diag(IdLoc, diag::ext_enum_value_not_int)
12470 << EnumVal.toString(10) << 1;
12471 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012472 }
12473 }
Mike Stump11289f42009-09-09 15:08:12 +000012474
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012475 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012476 // Make the enumerator value match the signedness and size of the
12477 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012478 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012479 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012480 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012481
Douglas Gregor954f6b272009-03-17 19:05:46 +000012482 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012483 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012484}
12485
12486
John McCall811a0f52010-10-22 23:36:17 +000012487Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12488 SourceLocation IdLoc, IdentifierInfo *Id,
12489 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012490 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012491 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012492 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012493 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012494
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012495 // The scope passed in may not be a decl scope. Zip up the scope tree until
12496 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012497 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012498
Chris Lattner8116d1b2007-01-25 22:38:29 +000012499 // Verify that there isn't already something declared with this name in this
12500 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012501 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012502 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012503 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012504 // Maybe we will complain about the shadowed template parameter.
12505 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12506 // Just pretend that we didn't see the previous declaration.
12507 PrevDecl = 0;
12508 }
12509
12510 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012511 // When in C++, we may get a TagDecl with the same name; in this case the
12512 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012513 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012514 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012515 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012516 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012517 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012518 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012519 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012520 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012521 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012522 }
12523 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012524
Aaron Ballman24a10472012-07-19 03:12:23 +000012525 // C++ [class.mem]p15:
12526 // If T is the name of a class, then each of the following shall have a name
12527 // different from T:
12528 // - every enumerator of every member of class T that is an unscoped
12529 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012530 if (CXXRecordDecl *Record
12531 = dyn_cast<CXXRecordDecl>(
12532 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012533 if (!TheEnumDecl->isScoped() &&
12534 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012535 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12536
John McCall811a0f52010-10-22 23:36:17 +000012537 EnumConstantDecl *New =
12538 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012539
John McCall553c0792010-01-23 00:46:32 +000012540 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012541 // Process attributes.
12542 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12543
12544 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012545 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012546 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012547 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012548
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012549 ActOnDocumentableDecl(New);
12550
John McCall48871652010-08-21 09:40:31 +000012551 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012552}
12553
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012554// Returns true when the enum initial expression does not trigger the
12555// duplicate enum warning. A few common cases are exempted as follows:
12556// Element2 = Element1
12557// Element2 = Element1 + 1
12558// Element2 = Element1 - 1
12559// Where Element2 and Element1 are from the same enum.
12560static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12561 Expr *InitExpr = ECD->getInitExpr();
12562 if (!InitExpr)
12563 return true;
12564 InitExpr = InitExpr->IgnoreImpCasts();
12565
12566 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12567 if (!BO->isAdditiveOp())
12568 return true;
12569 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12570 if (!IL)
12571 return true;
12572 if (IL->getValue() != 1)
12573 return true;
12574
12575 InitExpr = BO->getLHS();
12576 }
12577
12578 // This checks if the elements are from the same enum.
12579 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12580 if (!DRE)
12581 return true;
12582
12583 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12584 if (!EnumConstant)
12585 return true;
12586
12587 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12588 Enum)
12589 return true;
12590
12591 return false;
12592}
12593
12594struct DupKey {
12595 int64_t val;
12596 bool isTombstoneOrEmptyKey;
12597 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12598 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12599};
12600
12601static DupKey GetDupKey(const llvm::APSInt& Val) {
12602 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12603 false);
12604}
12605
12606struct DenseMapInfoDupKey {
12607 static DupKey getEmptyKey() { return DupKey(0, true); }
12608 static DupKey getTombstoneKey() { return DupKey(1, true); }
12609 static unsigned getHashValue(const DupKey Key) {
12610 return (unsigned)(Key.val * 37);
12611 }
12612 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12613 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12614 LHS.val == RHS.val;
12615 }
12616};
12617
12618// Emits a warning when an element is implicitly set a value that
12619// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012620static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12621 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012622 QualType EnumType) {
12623 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12624 Enum->getLocation()) ==
12625 DiagnosticsEngine::Ignored)
12626 return;
12627 // Avoid anonymous enums
12628 if (!Enum->getIdentifier())
12629 return;
12630
12631 // Only check for small enums.
12632 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12633 return;
12634
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012635 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12636 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012637
12638 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12639 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12640 ValueToVectorMap;
12641
12642 DuplicatesVector DupVector;
12643 ValueToVectorMap EnumMap;
12644
12645 // Populate the EnumMap with all values represented by enum constants without
12646 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012647 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012648 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012649
12650 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12651 // this constant. Skip this enum since it may be ill-formed.
12652 if (!ECD) {
12653 return;
12654 }
12655
12656 if (ECD->getInitExpr())
12657 continue;
12658
12659 DupKey Key = GetDupKey(ECD->getInitVal());
12660 DeclOrVector &Entry = EnumMap[Key];
12661
12662 // First time encountering this value.
12663 if (Entry.isNull())
12664 Entry = ECD;
12665 }
12666
12667 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012668 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012669 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12670 if (!ValidDuplicateEnum(ECD, Enum))
12671 continue;
12672
12673 DupKey Key = GetDupKey(ECD->getInitVal());
12674
12675 DeclOrVector& Entry = EnumMap[Key];
12676 if (Entry.isNull())
12677 continue;
12678
12679 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12680 // Ensure constants are different.
12681 if (D == ECD)
12682 continue;
12683
12684 // Create new vector and push values onto it.
12685 ECDVector *Vec = new ECDVector();
12686 Vec->push_back(D);
12687 Vec->push_back(ECD);
12688
12689 // Update entry to point to the duplicates vector.
12690 Entry = Vec;
12691
12692 // Store the vector somewhere we can consult later for quick emission of
12693 // diagnostics.
12694 DupVector.push_back(Vec);
12695 continue;
12696 }
12697
12698 ECDVector *Vec = Entry.get<ECDVector*>();
12699 // Make sure constants are not added more than once.
12700 if (*Vec->begin() == ECD)
12701 continue;
12702
12703 Vec->push_back(ECD);
12704 }
12705
12706 // Emit diagnostics.
12707 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12708 DupVectorEnd = DupVector.end();
12709 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12710 ECDVector *Vec = *DupVectorIter;
12711 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12712
12713 // Emit warning for one enum constant.
12714 ECDVector::iterator I = Vec->begin();
12715 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12716 << (*I)->getName() << (*I)->getInitVal().toString(10)
12717 << (*I)->getSourceRange();
12718 ++I;
12719
12720 // Emit one note for each of the remaining enum constants with
12721 // the same value.
12722 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12723 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12724 << (*I)->getName() << (*I)->getInitVal().toString(10)
12725 << (*I)->getSourceRange();
12726 delete Vec;
12727 }
12728}
12729
Mike Stump6814d1c2009-05-16 07:06:02 +000012730void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012731 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012732 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012733 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012734 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012735 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012736
12737 if (Attr)
12738 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012739
Eli Friedmand0e60972009-12-11 01:34:50 +000012740 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012741 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012742 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012743 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012744 if (!ECD) continue;
12745
12746 ECD->setType(EnumType);
12747 }
12748
John McCall9aa35be2010-05-06 08:49:23 +000012749 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012750 return;
12751 }
12752
Chris Lattner67933c02007-08-28 05:10:31 +000012753 // TODO: If the result value doesn't fit in an int, it must be a long or long
12754 // long value. ISO C does not support this, but GCC does as an extension,
12755 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012756 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12757 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12758 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012759
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012760 // Verify that all the values are okay, compute the size of the values, and
12761 // reverse the list.
12762 unsigned NumNegativeBits = 0;
12763 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012764
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012765 // Keep track of whether all elements have type int.
12766 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012767
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012768 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012769 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012770 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012771 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012772
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012773 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012774
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012775 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012776 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012777 NumPositiveBits = std::max(NumPositiveBits,
12778 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012779 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012780 NumNegativeBits = std::max(NumNegativeBits,
12781 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012782
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012783 // Keep track of whether every enum element has type int (very commmon).
12784 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012785 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012786 }
Mike Stump11289f42009-09-09 15:08:12 +000012787
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012788 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012789 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012790 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012791
John McCall56774992009-12-09 09:09:27 +000012792 // C++0x N3000 [conv.prom]p3:
12793 // An rvalue of an unscoped enumeration type whose underlying
12794 // type is not fixed can be converted to an rvalue of the first
12795 // of the following types that can represent all the values of
12796 // the enumeration: int, unsigned int, long int, unsigned long
12797 // int, long long int, or unsigned long long int.
12798 // C99 6.4.4.3p2:
12799 // An identifier declared as an enumeration constant has type int.
12800 // The C99 rule is modified by a gcc extension
12801 QualType BestPromotionType;
12802
Aaron Ballman9ead1242013-12-19 02:39:40 +000012803 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012804 // -fshort-enums is the equivalent to specifying the packed attribute on all
12805 // enum definitions.
12806 if (LangOpts.ShortEnums)
12807 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012808
Douglas Gregor0bf31402010-10-08 23:50:27 +000012809 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012810 BestType = Enum->getIntegerType();
12811 if (BestType->isPromotableIntegerType())
12812 BestPromotionType = Context.getPromotedIntegerType(BestType);
12813 else
12814 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012815 // We don't need to set BestWidth, because BestType is going to be the type
12816 // of the enumerators, but we do anyway because otherwise some compilers
12817 // warn that it might be used uninitialized.
12818 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012819 }
12820 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012821 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012822 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012823 // If it's packed, check also if it fits a char or a short.
12824 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012825 BestType = Context.SignedCharTy;
12826 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012827 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012828 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012829 BestType = Context.ShortTy;
12830 BestWidth = ShortWidth;
12831 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012832 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012833 BestWidth = IntWidth;
12834 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012835 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012836
John McCall56774992009-12-09 09:09:27 +000012837 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012838 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012839 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012840 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012841
Chris Lattner3a370bf2007-08-29 17:31:48 +000012842 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012843 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12844 BestType = Context.LongLongTy;
12845 }
12846 }
John McCall56774992009-12-09 09:09:27 +000012847 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012848 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012849 // If there is no negative value, figure out the smallest type that fits
12850 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012851 // If it's packed, check also if it fits a char or a short.
12852 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012853 BestType = Context.UnsignedCharTy;
12854 BestPromotionType = Context.IntTy;
12855 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012856 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012857 BestType = Context.UnsignedShortTy;
12858 BestPromotionType = Context.IntTy;
12859 BestWidth = ShortWidth;
12860 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012861 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012862 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000012863 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012864 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012865 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012866 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000012867 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012868 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012869 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012870 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012871 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000012872 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012873 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012874 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012875 "How could an initializer get larger than ULL?");
12876 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012877 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012878 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012879 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012880 }
12881 }
Mike Stump11289f42009-09-09 15:08:12 +000012882
Chris Lattner3a370bf2007-08-29 17:31:48 +000012883 // Loop over all of the enumerator constants, changing their types to match
12884 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012885 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000012886 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012887 if (!ECD) continue; // Already issued a diagnostic.
12888
12889 // Standard C says the enumerators have int type, but we allow, as an
12890 // extension, the enumerators to be larger than int size. If each
12891 // enumerator value fits in an int, type it as an int, otherwise type it the
12892 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12893 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000012894
12895 // Determine whether the value fits into an int.
12896 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012897
12898 // If it fits into an integer type, force it. Otherwise force it to match
12899 // the enum decl type.
12900 QualType NewTy;
12901 unsigned NewWidth;
12902 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000012903 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000012904 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012905 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000012906 NewTy = Context.IntTy;
12907 NewWidth = IntWidth;
12908 NewSign = true;
12909 } else if (ECD->getType() == BestType) {
12910 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000012911 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012912 // C++ [dcl.enum]p4: Following the closing brace of an
12913 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012914 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012915 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012916 continue;
12917 } else {
12918 NewTy = BestType;
12919 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012920 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012921 }
12922
12923 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000012924 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012925 InitVal.setIsSigned(NewSign);
12926 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000012927
Chris Lattner3a370bf2007-08-29 17:31:48 +000012928 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000012929 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000012930 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000012931 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000012932 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000012933 ECD->getInitExpr(),
12934 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000012935 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000012936 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012937 // C++ [dcl.enum]p4: Following the closing brace of an
12938 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012939 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012940 ECD->setType(EnumType);
12941 else
12942 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012943 }
Mike Stump11289f42009-09-09 15:08:12 +000012944
John McCall9aa35be2010-05-06 08:49:23 +000012945 Enum->completeDefinition(BestType, BestPromotionType,
12946 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000012947
12948 // If we're declaring a function, ensure this decl isn't forgotten about -
12949 // it needs to go into the function scope.
12950 if (InFunctionDeclarator)
12951 DeclsInPrototypeScope.push_back(Enum);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012952
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012953 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000012954
12955 // Now that the enum type is defined, ensure it's not been underaligned.
12956 if (Enum->hasAttrs())
12957 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012958}
Chris Lattner1300fb92007-01-23 23:42:53 +000012959
Abramo Bagnara348823a2011-03-03 14:20:18 +000012960Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12961 SourceLocation StartLoc,
12962 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000012963 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000012964
Douglas Gregor278f52e2009-05-30 00:08:05 +000012965 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000012966 AsmString, StartLoc,
12967 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012968 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000012969 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000012970}
Eli Friedman5ed51982009-06-05 02:44:36 +000012971
Douglas Gregor22d09742012-01-03 18:04:46 +000012972DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12973 SourceLocation ImportLoc,
12974 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000012975 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000012976 Module::AllVisible,
12977 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000012978 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000012979 return true;
12980
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012981 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000012982 Module *ModCheck = Mod;
12983 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12984 // If we've run out of module parents, just drop the remaining identifiers.
12985 // We need the length to be consistent.
12986 if (!ModCheck)
12987 break;
12988 ModCheck = ModCheck->Parent;
12989
12990 IdentifierLocs.push_back(Path[I].second);
12991 }
12992
12993 ImportDecl *Import = ImportDecl::Create(Context,
12994 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000012995 AtLoc.isValid()? AtLoc : ImportLoc,
12996 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000012997 Context.getTranslationUnitDecl()->addDecl(Import);
12998 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000012999}
13000
Richard Smithce587f52013-11-15 04:24:58 +000013001void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13002 // FIXME: Should we synthesize an ImportDecl here?
13003 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13004 /*Complain=*/true);
13005}
13006
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013007void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
13008 // Create the implicit import declaration.
13009 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13010 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13011 Loc, Mod, Loc);
13012 TU->addDecl(ImportD);
13013 Consumer.HandleImplicitImportDecl(ImportD);
13014
13015 // Make the module visible.
Douglas Gregorfb912652013-03-20 21:10:35 +000013016 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13017 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013018}
13019
David Chisnall0867d9c2012-02-18 16:12:34 +000013020void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13021 IdentifierInfo* AliasName,
13022 SourceLocation PragmaLoc,
13023 SourceLocation NameLoc,
13024 SourceLocation AliasNameLoc) {
13025 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13026 LookupOrdinaryName);
13027 AsmLabelAttr *Attr =
13028 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall0867d9c2012-02-18 16:12:34 +000013029
13030 if (PrevDecl)
13031 PrevDecl->addAttr(Attr);
13032 else
13033 (void)ExtnameUndeclaredIdentifiers.insert(
13034 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13035}
13036
Eli Friedman5ed51982009-06-05 02:44:36 +000013037void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13038 SourceLocation PragmaLoc,
13039 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013040 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013041
Eli Friedman5ed51982009-06-05 02:44:36 +000013042 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +000013043 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013044 } else {
13045 (void)WeakUndeclaredIdentifiers.insert(
13046 std::pair<IdentifierInfo*,WeakInfo>
13047 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013048 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013049}
13050
13051void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13052 IdentifierInfo* AliasName,
13053 SourceLocation PragmaLoc,
13054 SourceLocation NameLoc,
13055 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013056 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13057 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013058 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013059
Eli Friedman5ed51982009-06-05 02:44:36 +000013060 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013061 if (!PrevDecl->hasAttr<AliasAttr>())
13062 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013063 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013064 } else {
13065 (void)WeakUndeclaredIdentifiers.insert(
13066 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013067 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013068}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013069
13070Decl *Sema::getObjCDeclContext() const {
13071 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13072}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013073
13074AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013075 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013076 // If we are within an Objective-C method, we should consult
13077 // both the availability of the method as well as the
13078 // enclosing class. If the class is (say) deprecated,
13079 // the entire method is considered deprecated from the
13080 // purpose of checking if the current context is deprecated.
13081 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13082 AvailabilityResult R = MD->getAvailability();
13083 if (R != AR_Available)
13084 return R;
13085 D = MD->getClassInterface();
13086 }
13087 // If we are within an Objective-c @implementation, it
13088 // gets the same availability context as the @interface.
13089 else if (const ObjCImplementationDecl *ID =
13090 dyn_cast<ObjCImplementationDecl>(D)) {
13091 D = ID->getClassInterface();
13092 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013093 return D->getAvailability();
13094}