blob: 6d5e0f01268d6d88bc54916be0309869d2114946 [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)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000474 << (NestedNameSpecifier *)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.
873 if (isa<FunctionDecl>(DC)) {
874 DC = DC->getLexicalParent();
875
876 // A function not defined within a class will always return to its
877 // lexical context.
878 if (!isa<CXXRecordDecl>(DC))
879 return DC;
880
881 // A C++ inline method/friend is parsed *after* the topmost class
882 // it was declared in is fully parsed ("complete"); the topmost
883 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000884 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000885 DC = RD;
886
887 // Return the declaration context of the topmost class the inline method is
888 // declared in.
889 return DC;
890 }
891
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000892 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000893}
894
Douglas Gregor91f84212008-12-11 16:49:14 +0000895void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000896 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000897 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000898 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000899 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000900}
901
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000902void Sema::PopDeclContext() {
903 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000904
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000905 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000906 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000907}
908
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000909/// EnterDeclaratorContext - Used when we must lookup names in the context
910/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000911///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000912void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000913 // C++0x [basic.lookup.unqual]p13:
914 // A name used in the definition of a static data member of class
915 // X (after the qualified-id of the static member) is looked up as
916 // if the name was used in a member function of X.
917 // C++0x [basic.lookup.unqual]p14:
918 // If a variable member of a namespace is defined outside of the
919 // scope of its namespace then any name used in the definition of
920 // the variable member (after the declarator-id) is looked up as
921 // if the definition of the variable member occurred in its
922 // namespace.
923 // Both of these imply that we should push a scope whose context
924 // is the semantic context of the declaration. We can't use
925 // PushDeclContext here because that context is not necessarily
926 // lexically contained in the current context. Fortunately,
927 // the containing scope should have the appropriate information.
928
929 assert(!S->getEntity() && "scope already has entity");
930
931#ifndef NDEBUG
932 Scope *Ancestor = S->getParent();
933 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
934 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
935#endif
936
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000937 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000938 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000939}
940
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000941void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000942 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000943
John McCall6df5fef2009-12-19 10:49:29 +0000944 // Switch back to the lexical context. The safety of this is
945 // enforced by an assert in EnterDeclaratorContext.
946 Scope *Ancestor = S->getParent();
947 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +0000948 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +0000949
950 // We don't need to do anything with the scope, which is going to
951 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000952}
953
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000954
955void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
956 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
957 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
958 // We assume that the caller has already called
959 // ActOnReenterTemplateScope
960 FD = TFD->getTemplatedDecl();
961 }
962 if (!FD)
963 return;
964
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000965 // Same implementation as PushDeclContext, but enters the context
966 // from the lexical parent, rather than the top-level class.
967 assert(CurContext == FD->getLexicalParent() &&
968 "The next DeclContext should be lexically contained in the current one.");
969 CurContext = FD;
970 S->setEntity(CurContext);
971
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000972 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
973 ParmVarDecl *Param = FD->getParamDecl(P);
974 // If the parameter has an identifier, then add it to the scope
975 if (Param->getIdentifier()) {
976 S->AddDecl(Param);
977 IdResolver.AddDecl(Param);
978 }
979 }
980}
981
982
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000983void Sema::ActOnExitFunctionContext() {
984 // Same implementation as PopDeclContext, but returns to the lexical parent,
985 // rather than the top-level class.
986 assert(CurContext && "DeclContext imbalance!");
987 CurContext = CurContext->getLexicalParent();
988 assert(CurContext && "Popped translation unit!");
989}
990
991
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000992/// \brief Determine whether we allow overloading of the function
993/// PrevDecl with another declaration.
994///
995/// This routine determines whether overloading is possible, not
996/// whether some new function is actually an overload. It will return
997/// true in C++ (where we can always provide overloads) or, as an
998/// extension, in C when the previous function is already an
999/// overloaded function declaration or has the "overloadable"
1000/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001001static bool AllowOverloadingOfFunction(LookupResult &Previous,
1002 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001003 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001004 return true;
1005
John McCall1f82f242009-11-18 22:49:29 +00001006 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001007 return true;
1008
John McCall1f82f242009-11-18 22:49:29 +00001009 return (Previous.getResultKind() == LookupResult::Found
1010 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001011}
1012
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001013/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001014void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001015 // Move up the scope chain until we find the nearest enclosing
1016 // non-transparent context. The declaration will be introduced into this
1017 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001018 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001019 S = S->getParent();
1020
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001021 // Add scoped declarations into their context, so that they can be
1022 // found later. Declarations without a context won't be inserted
1023 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001024 if (AddToContext)
1025 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001026
Richard Smith541b38b2013-09-20 01:15:31 +00001027 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1028 // are function-local declarations.
1029 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001030 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001031 D->getLexicalDeclContext()->getRedeclContext()) &&
1032 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001033 return;
1034
1035 // Template instantiations should also not be pushed into scope.
1036 if (isa<FunctionDecl>(D) &&
1037 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001038 return;
1039
John McCall9f3059a2009-10-09 21:13:30 +00001040 // If this replaces anything in the current scope,
1041 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1042 IEnd = IdResolver.end();
1043 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001044 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1045 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001046 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001047
John McCall9f3059a2009-10-09 21:13:30 +00001048 // Should only need to replace one decl.
1049 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001050 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001051 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001052
John McCall48871652010-08-21 09:40:31 +00001053 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001054
1055 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1056 // Implicitly-generated labels may end up getting generated in an order that
1057 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1058 // the label at the appropriate place in the identifier chain.
1059 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001060 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001061 if (IDC == CurContext) {
1062 if (!S->isDeclScope(*I))
1063 continue;
1064 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001065 break;
1066 }
1067
Douglas Gregor46c04e72011-03-16 16:39:03 +00001068 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001069 } else {
1070 IdResolver.AddDecl(D);
1071 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001072}
1073
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001074void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1075 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1076 TUScope->AddDecl(D);
1077}
1078
Richard Smith1c34fb72013-08-13 18:18:50 +00001079bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Douglas Gregordb446112011-03-07 16:54:27 +00001080 bool ExplicitInstantiationOrSpecialization) {
Nico Weber555d1aa2012-12-17 03:51:09 +00001081 return IdResolver.isDeclInScope(D, Ctx, S,
Douglas Gregordb446112011-03-07 16:54:27 +00001082 ExplicitInstantiationOrSpecialization);
Douglas Gregor505ad492009-09-28 00:47:05 +00001083}
1084
John McCallcc14d1f2010-08-24 08:50:51 +00001085Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1086 DeclContext *TargetDC = DC->getPrimaryContext();
1087 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001088 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001089 if (ScopeDC->getPrimaryContext() == TargetDC)
1090 return S;
1091 } while ((S = S->getParent()));
1092
1093 return 0;
1094}
1095
John McCall1f82f242009-11-18 22:49:29 +00001096static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1097 DeclContext*,
1098 ASTContext&);
1099
1100/// Filters out lookup results that don't fall within the given scope
1101/// as determined by isDeclInScope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00001102void Sema::FilterLookupForScope(LookupResult &R,
1103 DeclContext *Ctx, Scope *S,
1104 bool ConsiderLinkage,
1105 bool ExplicitInstantiationOrSpecialization) {
John McCall1f82f242009-11-18 22:49:29 +00001106 LookupResult::Filter F = R.makeFilter();
1107 while (F.hasNext()) {
1108 NamedDecl *D = F.next();
1109
Richard Smith3f1b5d02011-05-05 21:57:07 +00001110 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall1f82f242009-11-18 22:49:29 +00001111 continue;
1112
1113 if (ConsiderLinkage &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00001114 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001115 continue;
1116
1117 F.erase();
1118 }
1119
1120 F.done();
1121}
1122
1123static bool isUsingDecl(NamedDecl *D) {
1124 return isa<UsingShadowDecl>(D) ||
1125 isa<UnresolvedUsingTypenameDecl>(D) ||
1126 isa<UnresolvedUsingValueDecl>(D);
1127}
1128
1129/// Removes using shadow declarations from the lookup results.
1130static void RemoveUsingDecls(LookupResult &R) {
1131 LookupResult::Filter F = R.makeFilter();
1132 while (F.hasNext())
1133 if (isUsingDecl(F.next()))
1134 F.erase();
1135
1136 F.done();
1137}
1138
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001139/// \brief Check for this common pattern:
1140/// @code
1141/// class S {
1142/// S(const S&); // DO NOT IMPLEMENT
1143/// void operator=(const S&); // DO NOT IMPLEMENT
1144/// };
1145/// @endcode
1146static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1147 // FIXME: Should check for private access too but access is set after we get
1148 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001149 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001150 return false;
1151
1152 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1153 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001154 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1155 return Method->isCopyAssignmentOperator();
1156 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001157}
1158
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001159// We need this to handle
1160//
1161// typedef struct {
1162// void *foo() { return 0; }
1163// } A;
1164//
1165// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1166// for example. If 'A', foo will have external linkage. If we have '*A',
1167// foo will have no linkage. Since we can't know untill we get to the end
1168// of the typedef, this function finds out if D might have non external linkage.
1169// Callers should verify at the end of the TU if it D has external linkage or
1170// not.
1171bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1172 const DeclContext *DC = D->getDeclContext();
1173 while (!DC->isTranslationUnit()) {
1174 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1175 if (!RD->hasNameForLinkage())
1176 return true;
1177 }
1178 DC = DC->getParent();
1179 }
1180
Rafael Espindola3ae00052013-05-13 00:12:11 +00001181 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001182}
1183
Eli Friedman5ef21752013-09-10 03:05:56 +00001184// FIXME: This needs to be refactored; some other isInMainFile users want
1185// these semantics.
1186static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1187 if (S.TUKind != TU_Complete)
1188 return false;
1189 return S.SourceMgr.isInMainFile(Loc);
1190}
1191
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001192bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1193 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001194
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001195 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1196 return false;
1197
1198 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001199 if (D->getDeclContext()->isDependentContext() ||
1200 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001201 return false;
1202
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001203 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001204 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1205 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001206
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001207 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1208 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1209 return false;
1210 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001211 // 'static inline' functions are defined in headers; don't warn.
1212 if (FD->isInlineSpecified() &&
1213 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001214 return false;
1215 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001216
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001217 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001218 Context.DeclMustBeEmitted(FD))
1219 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001220 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001221 // Constants and utility variables are defined in headers with internal
1222 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1223 // like "inline".)
1224 if (!isMainFileLoc(*this, VD->getLocation()))
1225 return false;
1226
Eli Friedman5ef21752013-09-10 03:05:56 +00001227 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001228 return false;
1229
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001230 if (VD->isStaticDataMember() &&
1231 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1232 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001233 } else {
1234 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001235 }
1236
John McCalld37d35b2010-10-27 01:41:35 +00001237 // Only warn for unused decls internal to the translation unit.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001238 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001239}
1240
1241void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001242 if (!D)
1243 return;
1244
1245 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001246 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001247 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1248 return; // First should already be in the vector.
1249 }
1250
1251 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001252 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001253 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1254 return; // First should already be in the vector.
1255 }
1256
David Blaikie3d8edc22012-05-26 05:35:39 +00001257 if (ShouldWarnIfUnusedFileScopedDecl(D))
1258 UnusedFileScopedDecls.push_back(D);
1259}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001260
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001261static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001262 if (D->isInvalidDecl())
1263 return false;
1264
Eli Friedmanc09e0552012-01-13 23:41:25 +00001265 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001266 return false;
John McCall67da35c2010-02-04 22:26:26 +00001267
Chris Lattnercab02a62011-02-17 20:34:02 +00001268 if (isa<LabelDecl>(D))
1269 return true;
1270
John McCall67da35c2010-02-04 22:26:26 +00001271 // White-list anything that isn't a local variable.
1272 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1273 !D->getDeclContext()->isFunctionOrMethod())
1274 return false;
1275
1276 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001277 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001278
1279 // White-list anything with an __attribute__((unused)) type.
1280 QualType Ty = VD->getType();
1281
1282 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001283 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001284 if (TT->getDecl()->hasAttr<UnusedAttr>())
1285 return false;
1286 }
1287
Douglas Gregor14f232e2010-05-08 23:05:03 +00001288 // If we failed to complete the type for some reason, or if the type is
1289 // dependent, don't diagnose the variable.
1290 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001291 return false;
1292
John McCallcef15822010-03-31 02:47:45 +00001293 if (const TagType *TT = Ty->getAs<TagType>()) {
1294 const TagDecl *Tag = TT->getDecl();
1295 if (Tag->hasAttr<UnusedAttr>())
1296 return false;
1297
1298 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001299 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001300 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001301
1302 if (const Expr *Init = VD->getInit()) {
David Blaikiea9d4a932012-10-24 21:29:06 +00001303 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1304 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001305 const CXXConstructExpr *Construct =
1306 dyn_cast<CXXConstructExpr>(Init);
1307 if (Construct && !Construct->isElidable()) {
1308 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001309 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001310 return false;
1311 }
1312 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001313 }
1314 }
John McCallcef15822010-03-31 02:47:45 +00001315
1316 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001317 }
1318
John McCall67da35c2010-02-04 22:26:26 +00001319 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001320}
1321
Anna Zaks964f4c62011-07-28 20:52:06 +00001322static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1323 FixItHint &Hint) {
1324 if (isa<LabelDecl>(D)) {
1325 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001326 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001327 if (AfterColon.isInvalid())
1328 return;
1329 Hint = FixItHint::CreateRemoval(CharSourceRange::
1330 getCharRange(D->getLocStart(), AfterColon));
1331 }
1332 return;
1333}
1334
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001335/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1336/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001337void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001338 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001339 if (!ShouldDiagnoseUnusedDecl(D))
1340 return;
1341
Anna Zaks964f4c62011-07-28 20:52:06 +00001342 GenerateFixForUnusedDecl(D, Context, Hint);
1343
Chris Lattnercab02a62011-02-17 20:34:02 +00001344 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001345 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001346 DiagID = diag::warn_unused_exception_param;
1347 else if (isa<LabelDecl>(D))
1348 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001349 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001350 DiagID = diag::warn_unused_variable;
1351
Anna Zaks964f4c62011-07-28 20:52:06 +00001352 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001353}
1354
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001355static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1356 // Verify that we have no forward references left. If so, there was a goto
1357 // or address of a label taken, but no definition of it. Label fwd
1358 // definitions are indicated with a null substmt.
1359 if (L->getStmt() == 0)
1360 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1361}
1362
Steve Naroffc62adb62007-10-09 22:01:59 +00001363void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001364 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001365 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001366 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001367
Chris Lattner302b4be2006-11-19 02:31:38 +00001368 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1369 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001370 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001371 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001372
Douglas Gregor91f84212008-12-11 16:49:14 +00001373 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1374 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001375
Douglas Gregor91f84212008-12-11 16:49:14 +00001376 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001377
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001378 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001379 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001380 DiagnoseUnusedDecl(D);
1381
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001382 // If this was a forward reference to a label, verify it was defined.
1383 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1384 CheckPoppedLabel(LD, *this);
1385
Douglas Gregor91f84212008-12-11 16:49:14 +00001386 // Remove this name from our lexical scope.
1387 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001388 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00001389 DiagnoseUnusedBackingIvarInAccessor(S);
Chris Lattner302b4be2006-11-19 02:31:38 +00001390}
1391
James Molloy6f8780b2012-02-29 10:24:19 +00001392void Sema::ActOnStartFunctionDeclarator() {
1393 ++InFunctionDeclarator;
1394}
1395
1396void Sema::ActOnEndFunctionDeclarator() {
1397 assert(InFunctionDeclarator);
1398 --InFunctionDeclarator;
1399}
1400
Douglas Gregor1c283312010-08-11 12:19:30 +00001401/// \brief Look for an Objective-C class in the translation unit.
1402///
1403/// \param Id The name of the Objective-C class we're looking for. If
1404/// typo-correction fixes this name, the Id will be updated
1405/// to the fixed name.
1406///
1407/// \param IdLoc The location of the name in the translation unit.
1408///
James Dennett41725122012-06-22 10:16:05 +00001409/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001410/// if there is no class with the given name.
1411///
1412/// \returns The declaration of the named Objective-C class, or NULL if the
1413/// class could not be found.
1414ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1415 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001416 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001417 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1418 // creation from this context.
1419 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1420
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001421 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001422 // Perform typo correction at the given location, but only if we
1423 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001424 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1425 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1426 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001427 Validator)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001428 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001429 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001430 Id = IDecl->getIdentifier();
1431 }
1432 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001433 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1434 // This routine must always return a class definition, if any.
1435 if (Def && Def->getDefinition())
1436 Def = Def->getDefinition();
1437 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001438}
1439
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001440/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1441/// from S, where a non-field would be declared. This routine copes
1442/// with the difference between C and C++ scoping rules in structs and
1443/// unions. For example, the following code is well-formed in C but
1444/// ill-formed in C++:
1445/// @code
1446/// struct S6 {
1447/// enum { BAR } e;
1448/// };
Mike Stump11289f42009-09-09 15:08:12 +00001449///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001450/// void test_S6() {
1451/// struct S6 a;
1452/// a.e = BAR;
1453/// }
1454/// @endcode
1455/// For the declaration of BAR, this routine will return a different
1456/// scope. The scope S will be the scope of the unnamed enumeration
1457/// within S6. In C++, this routine will return the scope associated
1458/// with S6, because the enumeration's scope is a transparent
1459/// context but structures can contain non-field names. In C, this
1460/// routine will return the translation unit scope, since the
1461/// enumeration's scope is a transparent context and structures cannot
1462/// contain non-field names.
1463Scope *Sema::getNonFieldDeclScope(Scope *S) {
1464 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001465 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001466 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001467 S = S->getParent();
1468 return S;
1469}
1470
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001471/// \brief Looks up the declaration of "struct objc_super" and
1472/// saves it for later use in building builtin declaration of
1473/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1474/// pre-existing declaration exists no action takes place.
1475static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1476 IdentifierInfo *II) {
1477 if (!II->isStr("objc_msgSendSuper"))
1478 return;
1479 ASTContext &Context = ThisSema.Context;
1480
1481 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1482 SourceLocation(), Sema::LookupTagName);
1483 ThisSema.LookupName(Result, S);
1484 if (Result.getResultKind() == LookupResult::Found)
1485 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1486 Context.setObjCSuperType(Context.getTagDeclType(TD));
1487}
1488
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001489/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1490/// file scope. lazily create a decl for it. ForRedeclaration is true
1491/// if we're creating this built-in in anticipation of redeclaring the
1492/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001493NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001494 Scope *S, bool ForRedeclaration,
1495 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001496 LookupPredefedObjCSuperType(*this, S, II);
1497
Chris Lattner9561a0b2007-01-28 08:20:04 +00001498 Builtin::ID BID = (Builtin::ID)bid;
1499
Chris Lattnerecd79c62009-06-14 00:45:47 +00001500 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001501 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001502 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001503 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001504 // Okay
1505 break;
1506
Mike Stump93246cc2009-07-28 23:57:15 +00001507 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001508 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001509 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001510 << Context.BuiltinInfo.GetName(BID);
1511 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001512
Mike Stump93246cc2009-07-28 23:57:15 +00001513 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001514 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001515 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001516 << Context.BuiltinInfo.GetName(BID);
1517 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001518
1519 case ASTContext::GE_Missing_ucontext:
1520 if (ForRedeclaration)
1521 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1522 << Context.BuiltinInfo.GetName(BID);
1523 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001524 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001525
1526 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1527 Diag(Loc, diag::ext_implicit_lib_function_decl)
1528 << Context.BuiltinInfo.GetName(BID)
1529 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001530 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001531 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001532 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001533 Diag(Loc, diag::note_please_include_header)
1534 << Context.BuiltinInfo.getHeaderName(BID)
1535 << Context.BuiltinInfo.GetName(BID);
1536 }
1537
Warren Hunt445d83e2013-11-01 23:46:51 +00001538 DeclContext *Parent = Context.getTranslationUnitDecl();
1539 if (getLangOpts().CPlusPlus) {
1540 LinkageSpecDecl *CLinkageDecl =
1541 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1542 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001543 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001544 Parent->addDecl(CLinkageDecl);
1545 Parent = CLinkageDecl;
1546 }
1547
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001548 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001549 Parent,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001550 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001551 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001552 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001553 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001554 New->setImplicit();
1555
Chris Lattner4dd27102008-05-05 22:18:14 +00001556 // Create Decl objects for each parameter, adding them to the
1557 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001558 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001559 SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001560 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1561 ParmVarDecl *parm =
1562 ParmVarDecl::Create(Context, New, SourceLocation(),
1563 SourceLocation(), 0,
1564 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001565 SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001566 parm->setScopeInfo(0, i);
1567 Params.push_back(parm);
1568 }
David Blaikie9c70e042011-09-21 18:16:56 +00001569 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001570 }
Mike Stump11289f42009-09-09 15:08:12 +00001571
1572 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001573 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001574
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001575 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001576 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1577 // relate Scopes to DeclContexts, and probably eliminate CurContext
1578 // entirely, but we're not there yet.
1579 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001580 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001581 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001582 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001583 return New;
1584}
1585
Douglas Gregor3552dab2013-01-09 00:47:56 +00001586/// \brief Filter out any previous declarations that the given declaration
1587/// should not consider because they are not permitted to conflict, e.g.,
1588/// because they come from hidden sub-modules and do not refer to the same
1589/// entity.
1590static void filterNonConflictingPreviousDecls(ASTContext &context,
1591 NamedDecl *decl,
1592 LookupResult &previous){
1593 // This is only interesting when modules are enabled.
1594 if (!context.getLangOpts().Modules)
1595 return;
1596
1597 // Empty sets are uninteresting.
1598 if (previous.empty())
1599 return;
1600
Douglas Gregor3552dab2013-01-09 00:47:56 +00001601 LookupResult::Filter filter = previous.makeFilter();
1602 while (filter.hasNext()) {
1603 NamedDecl *old = filter.next();
1604
1605 // Non-hidden declarations are never ignored.
1606 if (!old->isHidden())
1607 continue;
1608
Rafael Espindola3ae00052013-05-13 00:12:11 +00001609 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001610 filter.erase();
1611 }
1612
1613 filter.done();
1614}
1615
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001616bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1617 QualType OldType;
1618 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1619 OldType = OldTypedef->getUnderlyingType();
1620 else
1621 OldType = Context.getTypeDeclType(Old);
1622 QualType NewType = New->getUnderlyingType();
1623
Douglas Gregoraab36982012-01-11 22:33:48 +00001624 if (NewType->isVariablyModifiedType()) {
1625 // Must not redefine a typedef with a variably-modified type.
1626 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1627 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1628 << Kind << NewType;
1629 if (Old->getLocation().isValid())
1630 Diag(Old->getLocation(), diag::note_previous_definition);
1631 New->setInvalidDecl();
1632 return true;
1633 }
1634
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001635 if (OldType != NewType &&
1636 !OldType->isDependentType() &&
1637 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001638 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001639 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1640 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1641 << Kind << NewType << OldType;
1642 if (Old->getLocation().isValid())
1643 Diag(Old->getLocation(), diag::note_previous_definition);
1644 New->setInvalidDecl();
1645 return true;
1646 }
1647 return false;
1648}
1649
Richard Smithdda56e42011-04-15 14:24:37 +00001650/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001651/// same name and scope as a previous declaration 'Old'. Figure out
1652/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001653/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001654///
Richard Smithdda56e42011-04-15 14:24:37 +00001655void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001656 // If the new decl is known invalid already, don't bother doing any
1657 // merging checks.
1658 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001659
Steve Naroff44cfcb62008-09-09 14:32:20 +00001660 // Allow multiple definitions for ObjC built-in typedefs.
1661 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001662 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001663 const IdentifierInfo *TypeID = New->getIdentifier();
1664 switch (TypeID->getLength()) {
1665 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001666 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001667 {
1668 if (!TypeID->isStr("id"))
1669 break;
1670 QualType T = New->getUnderlyingType();
1671 if (!T->isPointerType())
1672 break;
1673 if (!T->isVoidPointerType()) {
1674 QualType PT = T->getAs<PointerType>()->getPointeeType();
1675 if (!PT->isStructureType())
1676 break;
1677 }
1678 Context.setObjCIdRedefinitionType(T);
1679 // Install the built-in type for 'id', ignoring the current definition.
1680 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1681 return;
1682 }
Chris Lattner66e32812008-11-20 05:41:43 +00001683 case 5:
1684 if (!TypeID->isStr("Class"))
1685 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001686 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001687 // Install the built-in type for 'Class', ignoring the current definition.
1688 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001689 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001690 case 3:
1691 if (!TypeID->isStr("SEL"))
1692 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001693 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001694 // Install the built-in type for 'SEL', ignoring the current definition.
1695 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001696 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001697 }
1698 // Fall through - the typedef name was not a builtin type.
1699 }
John McCall1f82f242009-11-18 22:49:29 +00001700
Douglas Gregorfb034662009-01-28 17:15:10 +00001701 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001702 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1703 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001704 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001705 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001706
1707 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001708 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001709 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001710
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001711 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001712 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001713
John McCall1f82f242009-11-18 22:49:29 +00001714 // If the old declaration is invalid, just give up here.
1715 if (Old->isInvalidDecl())
1716 return New->setInvalidDecl();
1717
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001718 // If the typedef types are not identical, reject them in all languages and
1719 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001720 if (isIncompatibleTypedef(Old, New))
1721 return;
Mike Stump11289f42009-09-09 15:08:12 +00001722
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001723 // The types match. Link up the redeclaration chain and merge attributes if
1724 // the old declaration was a typedef.
1725 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001726 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001727 mergeDeclAttributes(New, Old);
1728 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001729
David Blaikiebbafb8a2012-03-11 07:00:24 +00001730 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001731 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001732
David Blaikiebbafb8a2012-03-11 07:00:24 +00001733 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001734 // C++ [dcl.typedef]p2:
1735 // In a given non-class scope, a typedef specifier can be used to
1736 // redefine the name of any type declared in that scope to refer
1737 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001738 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001739 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001740
1741 // C++0x [dcl.typedef]p4:
1742 // In a given class scope, a typedef specifier can be used to redefine
1743 // any class-name declared in that scope that is not also a typedef-name
1744 // to refer to the type to which it already refers.
1745 //
1746 // This wording came in via DR424, which was a correction to the
1747 // wording in DR56, which accidentally banned code like:
1748 //
1749 // struct S {
1750 // typedef struct A { } A;
1751 // };
1752 //
1753 // in the C++03 standard. We implement the C++0x semantics, which
1754 // allow the above but disallow
1755 //
1756 // struct S {
1757 // typedef int I;
1758 // typedef int I;
1759 // };
1760 //
1761 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001762 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001763 return;
1764
Chris Lattner2581fc32009-04-17 22:04:20 +00001765 Diag(New->getLocation(), diag::err_redefinition)
1766 << New->getDeclName();
1767 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001768 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001769 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001770
Douglas Gregor7363fb02012-01-11 04:25:01 +00001771 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001772 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001773 return;
1774
Chris Lattner2581fc32009-04-17 22:04:20 +00001775 // If we have a redefinition of a typedef in C, emit a warning. This warning
1776 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001777 // -Wtypedef-redefinition. If either the original or the redefinition is
1778 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001779 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001780 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1781 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001782 return;
Mike Stump11289f42009-09-09 15:08:12 +00001783
Chris Lattner2581fc32009-04-17 22:04:20 +00001784 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1785 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001786 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001787 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001788}
1789
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001790/// DeclhasAttr - returns true if decl Declaration already has the target
1791/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001792static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001793DeclHasAttr(const Decl *D, const Attr *A) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00001794 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1795 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1796 // responsible for making sure they are consistent.
1797 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1798 if (AA)
1799 return false;
1800
DeLesley Hutchins2d0881b2012-10-12 21:38:12 +00001801 // The following thread safety attributes can also be duplicated.
1802 switch (A->getKind()) {
1803 case attr::ExclusiveLocksRequired:
1804 case attr::SharedLocksRequired:
1805 case attr::LocksExcluded:
1806 case attr::ExclusiveLockFunction:
1807 case attr::SharedLockFunction:
1808 case attr::UnlockFunction:
1809 case attr::ExclusiveTrylockFunction:
1810 case attr::SharedTrylockFunction:
1811 case attr::GuardedBy:
1812 case attr::PtGuardedBy:
1813 case attr::AcquiredBefore:
1814 case attr::AcquiredAfter:
1815 return false;
DeLesley Hutchins6c6e8592012-10-12 21:49:04 +00001816 default:
1817 ;
DeLesley Hutchins2d0881b2012-10-12 21:38:12 +00001818 }
1819
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001820 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001821 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001822 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1823 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001824 if (Ann) {
1825 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1826 return true;
1827 continue;
1828 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001829 // FIXME: Don't hardcode this check
1830 if (OA && isa<OwnershipAttr>(*i))
1831 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001832 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001833 }
Chris Lattner84966392008-03-03 03:28:21 +00001834
1835 return false;
1836}
1837
Richard Smithbc8caaf2013-02-22 04:55:39 +00001838static bool isAttributeTargetADefinition(Decl *D) {
1839 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1840 return VD->isThisDeclarationADefinition();
1841 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1842 return TD->isCompleteDefinition() || TD->isBeingDefined();
1843 return true;
1844}
1845
1846/// Merge alignment attributes from \p Old to \p New, taking into account the
1847/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1848///
1849/// \return \c true if any attributes were added to \p New.
1850static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1851 // Look for alignas attributes on Old, and pick out whichever attribute
1852 // specifies the strictest alignment requirement.
1853 AlignedAttr *OldAlignasAttr = 0;
1854 AlignedAttr *OldStrictestAlignAttr = 0;
1855 unsigned OldAlign = 0;
1856 for (specific_attr_iterator<AlignedAttr>
1857 I = Old->specific_attr_begin<AlignedAttr>(),
1858 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1859 // FIXME: We have no way of representing inherited dependent alignments
1860 // in a case like:
1861 // template<int A, int B> struct alignas(A) X;
1862 // template<int A, int B> struct alignas(B) X {};
1863 // For now, we just ignore any alignas attributes which are not on the
1864 // definition in such a case.
1865 if (I->isAlignmentDependent())
1866 return false;
1867
1868 if (I->isAlignas())
1869 OldAlignasAttr = *I;
1870
1871 unsigned Align = I->getAlignment(S.Context);
1872 if (Align > OldAlign) {
1873 OldAlign = Align;
1874 OldStrictestAlignAttr = *I;
1875 }
1876 }
1877
1878 // Look for alignas attributes on New.
1879 AlignedAttr *NewAlignasAttr = 0;
1880 unsigned NewAlign = 0;
1881 for (specific_attr_iterator<AlignedAttr>
1882 I = New->specific_attr_begin<AlignedAttr>(),
1883 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1884 if (I->isAlignmentDependent())
1885 return false;
1886
1887 if (I->isAlignas())
1888 NewAlignasAttr = *I;
1889
1890 unsigned Align = I->getAlignment(S.Context);
1891 if (Align > NewAlign)
1892 NewAlign = Align;
1893 }
1894
1895 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1896 // Both declarations have 'alignas' attributes. We require them to match.
1897 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1898 // fall short. (If two declarations both have alignas, they must both match
1899 // every definition, and so must match each other if there is a definition.)
1900
1901 // If either declaration only contains 'alignas(0)' specifiers, then it
1902 // specifies the natural alignment for the type.
1903 if (OldAlign == 0 || NewAlign == 0) {
1904 QualType Ty;
1905 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1906 Ty = VD->getType();
1907 else
1908 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1909
1910 if (OldAlign == 0)
1911 OldAlign = S.Context.getTypeAlign(Ty);
1912 if (NewAlign == 0)
1913 NewAlign = S.Context.getTypeAlign(Ty);
1914 }
1915
1916 if (OldAlign != NewAlign) {
1917 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1918 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1919 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1920 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1921 }
1922 }
1923
1924 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1925 // C++11 [dcl.align]p6:
1926 // if any declaration of an entity has an alignment-specifier,
1927 // every defining declaration of that entity shall specify an
1928 // equivalent alignment.
1929 // C11 6.7.5/7:
1930 // If the definition of an object does not have an alignment
1931 // specifier, any other declaration of that object shall also
1932 // have no alignment specifier.
1933 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1934 << OldAlignasAttr->isC11();
1935 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1936 << OldAlignasAttr->isC11();
1937 }
1938
1939 bool AnyAdded = false;
1940
1941 // Ensure we have an attribute representing the strictest alignment.
1942 if (OldAlign > NewAlign) {
1943 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1944 Clone->setInherited(true);
1945 New->addAttr(Clone);
1946 AnyAdded = true;
1947 }
1948
1949 // Ensure we have an alignas attribute if the old declaration had one.
1950 if (OldAlignasAttr && !NewAlignasAttr &&
1951 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1952 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1953 Clone->setInherited(true);
1954 New->addAttr(Clone);
1955 AnyAdded = true;
1956 }
1957
1958 return AnyAdded;
1959}
1960
1961static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1962 bool Override) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001963 InheritableAttr *NewAttr = NULL;
Michael Han99315932013-01-24 16:46:58 +00001964 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola19de5612013-01-12 06:42:30 +00001965 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001966 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1967 AA->getIntroduced(), AA->getDeprecated(),
1968 AA->getObsoleted(), AA->getUnavailable(),
1969 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001970 AttrSpellingListIndex);
Richard Smithbc8caaf2013-02-22 04:55:39 +00001971 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1972 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1973 AttrSpellingListIndex);
1974 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1975 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1976 AttrSpellingListIndex);
Rafael Espindola19de5612013-01-12 06:42:30 +00001977 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001978 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1979 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001980 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001981 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1982 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001983 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001984 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1985 FA->getFormatIdx(), FA->getFirstArg(),
1986 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001987 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001988 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1989 AttrSpellingListIndex);
1990 else if (isa<AlignedAttr>(Attr))
1991 // AlignedAttrs are handled separately, because we need to handle all
1992 // such attributes on a declaration at the same time.
1993 NewAttr = 0;
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001994 else if (!DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001995 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001996
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001997 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001998 NewAttr->setInherited(true);
1999 D->addAttr(NewAttr);
2000 return true;
2001 }
2002
2003 return false;
2004}
2005
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002006static const Decl *getDefinition(const Decl *D) {
2007 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00002008 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002009 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2010 const VarDecl *Def = VD->getDefinition();
2011 if (Def)
2012 return Def;
2013 return VD->getActingDefinition();
2014 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002015 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00002016 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002017 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00002018 return Def;
2019 }
2020 return NULL;
2021}
2022
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002023static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2024 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2025 I != E; ++I) {
2026 Attr *Attribute = *I;
2027 if (Attribute->getKind() == Kind)
2028 return true;
2029 }
2030 return false;
2031}
2032
2033/// checkNewAttributesAfterDef - If we already have a definition, check that
2034/// there are no new attributes in this declaration.
2035static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2036 if (!New->hasAttrs())
2037 return;
2038
2039 const Decl *Def = getDefinition(Old);
2040 if (!Def || Def == New)
2041 return;
2042
2043 AttrVec &NewAttributes = New->getAttrs();
2044 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2045 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002046
2047 if (isa<AliasAttr>(NewAttribute)) {
2048 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2049 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2050 else {
2051 VarDecl *VD = cast<VarDecl>(New);
2052 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2053 VarDecl::TentativeDefinition
2054 ? diag::err_alias_after_tentative
2055 : diag::err_redefinition;
2056 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2057 S.Diag(Def->getLocation(), diag::note_previous_definition);
2058 VD->setInvalidDecl();
2059 }
2060 ++I;
2061 continue;
2062 }
2063
2064 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2065 // Tentative definitions are only interesting for the alias check above.
2066 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2067 ++I;
2068 continue;
2069 }
2070 }
2071
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002072 if (hasAttribute(Def, NewAttribute->getKind())) {
2073 ++I;
2074 continue; // regular attr merging will take care of validating this.
2075 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002076
Richard Smithdebc59d2013-01-30 05:45:05 +00002077 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002078 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002079 ++I;
2080 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002081 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2082 if (AA->isAlignas()) {
2083 // C++11 [dcl.align]p6:
2084 // if any declaration of an entity has an alignment-specifier,
2085 // every defining declaration of that entity shall specify an
2086 // equivalent alignment.
2087 // C11 6.7.5/7:
2088 // If the definition of an object does not have an alignment
2089 // specifier, any other declaration of that object shall also
2090 // have no alignment specifier.
2091 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2092 << AA->isC11();
2093 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2094 << AA->isC11();
2095 NewAttributes.erase(NewAttributes.begin() + I);
2096 --E;
2097 continue;
2098 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002099 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002100
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002101 S.Diag(NewAttribute->getLocation(),
2102 diag::warn_attribute_precede_definition);
2103 S.Diag(Def->getLocation(), diag::note_previous_definition);
2104 NewAttributes.erase(NewAttributes.begin() + I);
2105 --E;
2106 }
2107}
2108
John McCallf79e87d2011-03-02 04:00:57 +00002109/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002110void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002111 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002112 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2113 UsedAttr *NewAttr = OldAttr->clone(Context);
2114 NewAttr->setInherited(true);
2115 New->addAttr(NewAttr);
2116 }
2117
Richard Smithe233fbf2013-01-28 22:42:45 +00002118 if (!Old->hasAttrs() && !New->hasAttrs())
2119 return;
2120
Rafael Espindola36191042012-05-18 01:47:00 +00002121 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002122 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002123
Douglas Gregor32c17572012-01-01 20:30:41 +00002124 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002125 return;
John McCallf79e87d2011-03-02 04:00:57 +00002126
Douglas Gregor32c17572012-01-01 20:30:41 +00002127 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002128
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002129 // Ensure that any moving of objects within the allocated map is done before
2130 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002131 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002132
Peter Collingbourneab8bc062011-01-21 02:08:36 +00002133 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor32c17572012-01-01 20:30:41 +00002134 i = Old->specific_attr_begin<InheritableAttr>(),
2135 e = Old->specific_attr_end<InheritableAttr>();
2136 i != e; ++i) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002137 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002138 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002139 if (isa<DeprecatedAttr>(*i) ||
2140 isa<UnavailableAttr>(*i) ||
2141 isa<AvailabilityAttr>(*i)) {
2142 switch (AMK) {
2143 case AMK_None:
2144 continue;
John McCalld2930c22011-07-22 02:45:48 +00002145
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002146 case AMK_Redeclaration:
2147 break;
2148
2149 case AMK_Override:
2150 Override = true;
2151 break;
2152 }
2153 }
2154
Rafael Espindolab0938852013-10-25 01:28:12 +00002155 // Already handled.
2156 if (isa<UsedAttr>(*i))
2157 continue;
2158
Richard Smithbc8caaf2013-02-22 04:55:39 +00002159 if (mergeDeclAttribute(*this, New, *i, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002160 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002161 }
John McCallf79e87d2011-03-02 04:00:57 +00002162
Richard Smithbc8caaf2013-02-22 04:55:39 +00002163 if (mergeAlignedAttrs(*this, New, Old))
2164 foundAny = true;
2165
Douglas Gregor32c17572012-01-01 20:30:41 +00002166 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002167}
2168
2169/// mergeParamDeclAttributes - Copy attributes from the old parameter
2170/// to the new one.
2171static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2172 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002173 Sema &S) {
2174 // C++11 [dcl.attr.depend]p2:
2175 // The first declaration of a function shall specify the
2176 // carries_dependency attribute for its declarator-id if any declaration
2177 // of the function specifies the carries_dependency attribute.
2178 if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2179 !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2180 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2181 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2182 // Find the first declaration of the parameter.
2183 // FIXME: Should we build redeclaration chains for function parameters?
2184 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002185 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002186 const ParmVarDecl *FirstVD =
2187 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2188 S.Diag(FirstVD->getLocation(),
2189 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2190 }
2191
John McCallf79e87d2011-03-02 04:00:57 +00002192 if (!oldDecl->hasAttrs())
2193 return;
2194
2195 bool foundAny = newDecl->hasAttrs();
2196
2197 // Ensure that any moving of objects within the allocated map is
2198 // done before we process them.
2199 if (!foundAny) newDecl->setAttrs(AttrVec());
2200
2201 for (specific_attr_iterator<InheritableParamAttr>
2202 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2203 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2204 if (!DeclHasAttr(newDecl, *i)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002205 InheritableAttr *newAttr =
2206 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002207 newAttr->setInherited(true);
2208 newDecl->addAttr(newAttr);
2209 foundAny = true;
2210 }
2211 }
2212
2213 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002214}
2215
Dan Gohman28ade552010-07-26 21:25:24 +00002216namespace {
2217
Douglas Gregora74a2972009-03-06 22:43:54 +00002218/// Used in MergeFunctionDecl to keep track of function parameters in
2219/// C.
2220struct GNUCompatibleParamWarning {
2221 ParmVarDecl *OldParm;
2222 ParmVarDecl *NewParm;
2223 QualType PromotedType;
2224};
2225
Dan Gohman28ade552010-07-26 21:25:24 +00002226}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002227
2228/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002229Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002230 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002231 if (Ctor->isDefaultConstructor())
2232 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002233
2234 if (Ctor->isCopyConstructor())
2235 return Sema::CXXCopyConstructor;
2236
2237 if (Ctor->isMoveConstructor())
2238 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002239 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002240 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002241 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002242 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002243 } else if (MD->isMoveAssignmentOperator()) {
2244 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002245 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002246
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002247 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002248}
2249
Sebastian Redl243d9052010-06-09 21:17:41 +00002250/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002251/// only extern inline functions can be redefined, and even then only in
2252/// GNU89 mode.
2253static bool canRedefineFunction(const FunctionDecl *FD,
2254 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002255 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2256 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002257 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002258 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002259}
2260
Reid Kleckner78af0702013-08-27 23:08:25 +00002261const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2262 const AttributedType *AT = T->getAs<AttributedType>();
2263 while (AT && !AT->isCallingConv())
2264 AT = AT->getModifiedType()->getAs<AttributedType>();
2265 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002266}
2267
Benjamin Kramer3e350262013-02-15 12:30:38 +00002268template <typename T>
2269static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002270 const DeclContext *DC = Old->getDeclContext();
2271 if (DC->isRecord())
2272 return false;
2273
2274 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002275 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002276 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002277 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002278 return true;
2279 return false;
2280}
2281
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002282/// MergeFunctionDecl - We just parsed a function 'New' from
2283/// declarator D which has the same name and scope as a previous
2284/// declaration 'Old'. Figure out how to resolve this situation,
2285/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002286///
2287/// In C++, New and Old must be declarations that are not
2288/// overloaded. Use IsOverload to determine whether New and Old are
2289/// overloaded, and to select the Old declaration that New should be
2290/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002291///
2292/// Returns true if there was an error, false otherwise.
Richard Smith1c34fb72013-08-13 18:18:50 +00002293bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2294 bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002295 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002296 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002297 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002298 = dyn_cast<FunctionTemplateDecl>(OldD))
2299 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002300 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002301 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00002302 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002303 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002304 if (New->getFriendObjectKind()) {
2305 Diag(New->getLocation(), diag::err_using_decl_friend);
2306 Diag(Shadow->getTargetDecl()->getLocation(),
2307 diag::note_using_decl_target);
2308 Diag(Shadow->getUsingDecl()->getLocation(),
2309 diag::note_using_decl) << 0;
2310 return true;
2311 }
2312
John McCalle29c5cd2009-12-10 19:51:03 +00002313 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2314 Diag(Shadow->getTargetDecl()->getLocation(),
2315 diag::note_using_decl_target);
2316 Diag(Shadow->getUsingDecl()->getLocation(),
2317 diag::note_using_decl) << 0;
2318 return true;
2319 }
2320
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002321 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002322 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002323 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002324 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00002325 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002326
David Majnemerea5092a2013-07-07 23:49:50 +00002327 // If the old declaration is invalid, just give up here.
2328 if (Old->isInvalidDecl())
2329 return true;
2330
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002331 // Determine whether the previous declaration was a definition,
2332 // implicit declaration, or a declaration.
2333 diag::kind PrevDiag;
2334 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002335 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002336 else if (Old->isImplicit())
2337 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002338 else
Chris Lattner0369c572008-11-23 23:12:31 +00002339 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002340
Charles Davisfea48452010-02-18 02:00:42 +00002341 // Don't complain about this if we're in GNU89 mode and the old function
2342 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002343 // Don't complain about specializations. They are not supposed to have
2344 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002345 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002346 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002347 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002348 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002349 !canRedefineFunction(Old, getLangOpts())) {
2350 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002351 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2352 Diag(Old->getLocation(), PrevDiag);
2353 } else {
2354 Diag(New->getLocation(), diag::err_static_non_static) << New;
2355 Diag(Old->getLocation(), PrevDiag);
2356 return true;
2357 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002358 }
2359
Reid Kleckner78af0702013-08-27 23:08:25 +00002360
2361 // If a function is first declared with a calling convention, but is later
2362 // declared or defined without one, all following decls assume the calling
2363 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002364 //
John McCalla5f46fb2012-08-25 02:00:03 +00002365 // It's OK if a function is first declared without a calling convention,
2366 // but is later declared or defined with the default calling convention.
2367 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002368 // To test if either decl has an explicit calling convention, we look for
2369 // AttributedType sugar nodes on the type as written. If they are missing or
2370 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002371 //
2372 // Note also that we DO NOT return at this point, because we still have
2373 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002374 QualType OldQType = Context.getCanonicalType(Old->getType());
2375 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002376 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002377 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002378 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2379 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2380 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002381
Reid Kleckner78af0702013-08-27 23:08:25 +00002382 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002383 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002384 const FunctionType *FT =
2385 First->getType().getCanonicalType()->castAs<FunctionType>();
2386 FunctionType::ExtInfo FI = FT->getExtInfo();
2387 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2388 if (!NewCCExplicit) {
2389 // Inherit the CC from the previous declaration if it was specified
2390 // there but not here.
2391 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2392 RequiresAdjustment = true;
2393 } else {
2394 // Calling conventions aren't compatible, so complain.
2395 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2396 Diag(New->getLocation(), diag::err_cconv_change)
2397 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2398 << !FirstCCExplicit
2399 << (!FirstCCExplicit ? "" :
2400 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002401
Reid Kleckner78af0702013-08-27 23:08:25 +00002402 // Put the note on the first decl, since it is the one that matters.
2403 Diag(First->getLocation(), diag::note_previous_declaration);
2404 return true;
2405 }
John McCallcddbad02010-02-04 05:44:44 +00002406 }
2407
John McCallab26cfa2010-02-05 21:31:56 +00002408 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002409 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2410 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2411 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002412 }
2413
Douglas Gregor77e274f2010-06-18 21:30:25 +00002414 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002415 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2416 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2417 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002418 Diag(New->getLocation(), diag::err_regparm_mismatch)
2419 << NewType->getRegParmType()
2420 << OldType->getRegParmType();
2421 Diag(Old->getLocation(), diag::note_previous_declaration);
2422 return true;
2423 }
John McCall4f5019e2010-12-19 02:44:49 +00002424
2425 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2426 RequiresAdjustment = true;
2427 }
2428
Douglas Gregorf1404d72011-10-14 15:55:40 +00002429 // Merge ns_returns_retained attribute.
2430 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2431 if (NewTypeInfo.getProducesResult()) {
2432 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2433 Diag(Old->getLocation(), diag::note_previous_declaration);
2434 return true;
2435 }
2436
2437 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2438 RequiresAdjustment = true;
2439 }
2440
John McCall4f5019e2010-12-19 02:44:49 +00002441 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002442 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2443 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2444 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002445 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002446 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002447 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002448
2449 // If this redeclaration makes the function inline, we may need to add it to
2450 // UndefinedButUsed.
2451 if (!Old->isInlined() && New->isInlined() &&
2452 !New->hasAttr<GNUInlineAttr>() &&
2453 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2454 Old->isUsed(false) &&
2455 !Old->isDefined() && !New->isThisDeclarationADefinition())
2456 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2457 SourceLocation()));
2458
2459 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2460 // about it.
2461 if (New->hasAttr<GNUInlineAttr>() &&
2462 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2463 UndefinedButUsed.erase(Old->getCanonicalDecl());
2464 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002465
David Blaikiebbafb8a2012-03-11 07:00:24 +00002466 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002467 // (C++98 13.1p2):
2468 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002469 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002470 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002471
2472 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002473 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002474 // Redeclarations or specializations of a function or function template
2475 // with a declared return type that uses a placeholder type shall also
2476 // use that placeholder, not a deduced type.
2477 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2478 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2479 : OldType)->getResultType();
2480 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2481 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2482 : NewType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002483 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002484 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2485 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2486 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002487 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2488 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002489 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2490 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002491 if (New->isCXXClassMember() && New->isOutOfLine())
2492 Diag(New->getLocation(),
2493 diag::err_member_def_does_not_match_ret_type) << New;
2494 else
2495 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002496 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2497 return true;
2498 }
2499 else
2500 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002501 }
2502
Richard Smith2a7d4812013-05-04 07:00:32 +00002503 QualType OldReturnType = OldType->getResultType();
2504 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2505 if (OldReturnType != NewReturnType) {
2506 // If this function has a deduced return type and has already been
2507 // defined, copy the deduced value from the old declaration.
2508 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2509 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002510 New->setType(
2511 SubstAutoType(New->getType(),
2512 OldAT->isDependentType() ? Context.DependentTy
2513 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002514 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002515 SubstAutoType(NewQType,
2516 OldAT->isDependentType() ? Context.DependentTy
2517 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002518 }
2519 }
2520
2521 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2522 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002523 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002524 // Preserve triviality.
2525 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002526
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002527 // MSVC allows explicit template specialization at class scope:
2528 // 2 CXMethodDecls referring to the same function will be injected.
2529 // We don't want a redeclartion error.
2530 bool IsClassScopeExplicitSpecialization =
2531 OldMethod->isFunctionTemplateSpecialization() &&
2532 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002533 bool isFriend = NewMethod->getFriendObjectKind();
2534
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002535 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2536 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002537 // -- Member function declarations with the same name and the
2538 // same parameter types cannot be overloaded if any of them
2539 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002540 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002541 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2542 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2543 return true;
2544 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002545
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002546 // C++ [class.mem]p1:
2547 // [...] A member shall not be declared twice in the
2548 // member-specification, except that a nested class or member
2549 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002550 if (ActiveTemplateInstantiations.empty()) {
2551 unsigned NewDiag;
2552 if (isa<CXXConstructorDecl>(OldMethod))
2553 NewDiag = diag::err_constructor_redeclared;
2554 else if (isa<CXXDestructorDecl>(NewMethod))
2555 NewDiag = diag::err_destructor_redeclared;
2556 else if (isa<CXXConversionDecl>(NewMethod))
2557 NewDiag = diag::err_conv_function_redeclared;
2558 else
2559 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002560
Richard Smith57e7ff92012-07-13 04:12:04 +00002561 Diag(New->getLocation(), NewDiag);
2562 } else {
2563 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2564 << New << New->getType();
2565 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002566 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002567
2568 // Complain if this is an explicit declaration of a special
2569 // member that was initially declared implicitly.
2570 //
2571 // As an exception, it's okay to befriend such methods in order
2572 // to permit the implicit constructor/destructor/operator calls.
2573 } else if (OldMethod->isImplicit()) {
2574 if (isFriend) {
2575 NewMethod->setImplicit();
2576 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002577 Diag(NewMethod->getLocation(),
2578 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002579 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002580 return true;
2581 }
Richard Smith337a5a12012-06-08 01:30:54 +00002582 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002583 Diag(NewMethod->getLocation(),
2584 diag::err_definition_of_explicitly_defaulted_member)
2585 << getSpecialMember(OldMethod);
2586 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002587 }
2588 }
2589
Richard Smith10876ef2013-01-17 01:30:42 +00002590 // C++11 [dcl.attr.noreturn]p1:
2591 // The first declaration of a function shall specify the noreturn
2592 // attribute if any declaration of that function specifies the noreturn
2593 // attribute.
2594 if (New->hasAttr<CXX11NoReturnAttr>() &&
2595 !Old->hasAttr<CXX11NoReturnAttr>()) {
2596 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2597 diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002598 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002599 diag::note_noreturn_missing_first_decl);
2600 }
2601
Richard Smithe233fbf2013-01-28 22:42:45 +00002602 // C++11 [dcl.attr.depend]p2:
2603 // The first declaration of a function shall specify the
2604 // carries_dependency attribute for its declarator-id if any declaration
2605 // of the function specifies the carries_dependency attribute.
2606 if (New->hasAttr<CarriesDependencyAttr>() &&
2607 !Old->hasAttr<CarriesDependencyAttr>()) {
2608 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2609 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002610 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002611 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2612 }
2613
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002614 // (C++98 8.3.5p3):
2615 // All declarations for a function shall agree exactly in both the
2616 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002617 // We also want to respect all the extended bits except noreturn.
2618
2619 // noreturn should now match unless the old type info didn't have it.
2620 QualType OldQTypeForComparison = OldQType;
2621 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2622 assert(OldQType == QualType(OldType, 0));
2623 const FunctionType *OldTypeForComparison
2624 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2625 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2626 assert(OldQTypeForComparison.isCanonical());
2627 }
2628
Rafael Espindolaf4187652013-02-14 01:18:37 +00002629 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002630 // As a special case, retain the language linkage from previous
2631 // declarations of a friend function as an extension.
2632 //
2633 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2634 // and is useful because there's otherwise no way to specify language
2635 // linkage within class scope.
2636 //
2637 // Check cautiously as the friend object kind isn't yet complete.
2638 if (New->getFriendObjectKind() != Decl::FOK_None) {
2639 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2640 Diag(Old->getLocation(), PrevDiag);
2641 } else {
2642 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2643 Diag(Old->getLocation(), PrevDiag);
2644 return true;
2645 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002646 }
2647
John McCall4f5019e2010-12-19 02:44:49 +00002648 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002649 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002650
Richard Smith541b38b2013-09-20 01:15:31 +00002651 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2652 New->isLocalExternDecl()) {
2653 // It's OK if we couldn't merge types for a local function declaraton
2654 // if either the old or new type is dependent. We'll merge the types
2655 // when we instantiate the function.
2656 return false;
2657 }
2658
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002659 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002660 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002661
2662 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002663 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002664 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002665 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002666 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2667 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002668 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002669 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002670 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002671 // The old declaration provided a function prototype, but the
2672 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002673 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002674 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002675 OldProto->arg_type_end());
2676 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002677 ParamTypes,
John McCalldb40c7f2010-12-14 08:05:40 +00002678 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002679 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002680 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002681
2682 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002683 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00002684 for (FunctionProtoType::arg_type_iterator
2685 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002686 ParamEnd = OldProto->arg_type_end();
2687 ParamType != ParamEnd; ++ParamType) {
2688 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002689 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002690 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002691 *ParamType, /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002692 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002693 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002694 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002695 Param->setImplicit();
2696 Params.push_back(Param);
2697 }
2698
David Blaikie9c70e042011-09-21 18:16:56 +00002699 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002700 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002701
Richard Smith1c34fb72013-08-13 18:18:50 +00002702 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002703 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002704
Douglas Gregora74a2972009-03-06 22:43:54 +00002705 // GNU C permits a K&R definition to follow a prototype declaration
2706 // if the declared types of the parameters in the K&R definition
2707 // match the types in the prototype declaration, even when the
2708 // promoted types of the parameters from the K&R definition differ
2709 // from the types in the prototype. GCC then keeps the types from
2710 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002711 //
2712 // If a variadic prototype is followed by a non-variadic K&R definition,
2713 // the K&R definition becomes variadic. This is sort of an edge case, but
2714 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2715 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002716 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002717 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002718 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002719 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002720 SmallVector<QualType, 16> ArgTypes;
2721 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002722 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002723 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002724 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002725 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002726
Douglas Gregora74a2972009-03-06 22:43:54 +00002727 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002728 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2729 NewProto->getResultType());
2730 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002731 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002732 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002733 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2734 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002735 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00002736 NewProto->getArgType(Idx))) {
2737 ArgTypes.push_back(NewParm->getType());
2738 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002739 NewParm->getType(),
2740 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00002741 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00002742 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2743 Warnings.push_back(Warn);
2744 ArgTypes.push_back(NewParm->getType());
2745 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002746 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002747 }
2748
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002749 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002750 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2751 Diag(Warnings[Warn].NewParm->getLocation(),
2752 diag::ext_param_promoted_not_compatible_with_prototype)
2753 << Warnings[Warn].PromotedType
2754 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002755 if (Warnings[Warn].OldParm->getLocation().isValid())
2756 Diag(Warnings[Warn].OldParm->getLocation(),
2757 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002758 }
2759
Richard Smith1c34fb72013-08-13 18:18:50 +00002760 if (MergeTypeWithOld)
2761 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2762 OldProto->getExtProtoInfo()));
2763 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002764 }
2765
2766 // Fall through to diagnose conflicting types.
2767 }
2768
John McCallad327cd2013-04-14 08:50:55 +00002769 // A function that has already been declared has been redeclared or
2770 // defined with a different type; show an appropriate diagnostic.
2771
2772 // If the previous declaration was an implicitly-generated builtin
2773 // declaration, then at the very least we should use a specialized note.
2774 unsigned BuiltinID;
2775 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2776 // If it's actually a library-defined builtin function like 'malloc'
2777 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002778 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002779 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2780 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2781 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002782
2783 // If this is a global redeclaration, just forget hereafter
2784 // about the "builtin-ness" of the function.
2785 //
2786 // Doing this for local extern declarations is problematic. If
2787 // the builtin declaration remains visible, a second invalid
2788 // local declaration will produce a hard error; if it doesn't
2789 // remain visible, a single bogus local redeclaration (which is
2790 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002791 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002792 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2793
Douglas Gregor893c2c92009-03-23 17:47:24 +00002794 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002795 }
Steve Naroff17832a42008-01-16 15:01:34 +00002796
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002797 PrevDiag = diag::note_previous_builtin_declaration;
2798 }
2799
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002800 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002801 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002802 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002803}
2804
Douglas Gregore62c0a42009-02-24 01:23:02 +00002805/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002806/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002807///
2808/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002809/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002810/// the new declaration, once we know that New is in fact a
2811/// redeclaration of Old.
2812///
2813/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002814bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002815 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002816 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002817 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002818
Douglas Gregore62c0a42009-02-24 01:23:02 +00002819 // Merge "pure" flag.
2820 if (Old->isPure())
2821 New->setPure();
2822
Rafael Espindolabefe1302012-11-25 14:07:59 +00002823 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002824 if (Old->getMostRecentDecl()->isUsed(false))
2825 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002826
John McCallf79e87d2011-03-02 04:00:57 +00002827 // Merge attributes from the parameters. These can mismatch with K&R
2828 // declarations.
2829 if (New->getNumParams() == Old->getNumParams())
2830 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2831 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002832 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002833
David Blaikiebbafb8a2012-03-11 07:00:24 +00002834 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002835 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002836
Rafael Espindola8778c282012-11-29 16:09:03 +00002837 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002838 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2839 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002840 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002841 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002842 New->setType(Merged);
2843
Douglas Gregore62c0a42009-02-24 01:23:02 +00002844 return false;
2845}
2846
John McCall31168b02011-06-15 23:02:42 +00002847
John McCallf79e87d2011-03-02 04:00:57 +00002848void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002849 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002850
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002851 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002852 AvailabilityMergeKind MergeKind =
2853 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2854 : AMK_Override;
2855 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002856
2857 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002858 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2859 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002860 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002861 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002862 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002863 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002864
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002865 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002866}
2867
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002868/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2869/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002870/// emitting diagnostics as appropriate.
2871///
2872/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002873/// to here in AddInitializerToDecl. We can't check them before the initializer
2874/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002875void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2876 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002877 if (New->isInvalidDecl() || Old->isInvalidDecl())
2878 return;
2879
2880 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002881 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002882 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002883 // We don't know what the new type is until the initializer is attached.
2884 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002885 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2886 // These could still be something that needs exception specs checked.
2887 return MergeVarDeclExceptionSpecs(New, Old);
2888 }
Richard Smith30482bc2011-02-20 03:19:35 +00002889 // C++ [basic.link]p10:
2890 // [...] the types specified by all declarations referring to a given
2891 // object or function shall be identical, except that declarations for an
2892 // array object can specify array types that differ by the presence or
2893 // absence of a major array bound (8.3.4).
2894 else if (Old->getType()->isIncompleteArrayType() &&
2895 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002896 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2897 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2898 if (Context.hasSameType(OldArray->getElementType(),
2899 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002900 MergedT = New->getType();
2901 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002902 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002903 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2904 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2905 if (Context.hasSameType(OldArray->getElementType(),
2906 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002907 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002908 } else if (New->getType()->isObjCObjectPointerType() &&
2909 Old->getType()->isObjCObjectPointerType()) {
2910 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2911 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002912 }
2913 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002914 // C 6.2.7p2:
2915 // All declarations that refer to the same object or function shall have
2916 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002917 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2918 }
2919 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002920 // It's OK if we couldn't merge types if either type is dependent, for a
2921 // block-scope variable. In other cases (static data members of class
2922 // templates, variable templates, ...), we require the types to be
2923 // equivalent.
2924 // FIXME: The C++ standard doesn't say anything about this.
2925 if ((New->getType()->isDependentType() ||
2926 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2927 // If the old type was dependent, we can't merge with it, so the new type
2928 // becomes dependent for now. We'll reproduce the original type when we
2929 // instantiate the TypeSourceInfo for the variable.
2930 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2931 New->setType(Context.DependentTy);
2932 return;
2933 }
2934
2935 // FIXME: Even if this merging succeeds, some other non-visible declaration
2936 // of this variable might have an incompatible type. For instance:
2937 //
2938 // extern int arr[];
2939 // void f() { extern int arr[2]; }
2940 // void g() { extern int arr[3]; }
2941 //
2942 // Neither C nor C++ requires a diagnostic for this, but we should still try
2943 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002944 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002945 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002946 Diag(Old->getLocation(), diag::note_previous_definition);
2947 return New->setInvalidDecl();
2948 }
John McCallb65e8fe2013-04-01 18:34:28 +00002949
2950 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002951 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002952 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002953 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002954}
2955
Richard Smith3c785782013-09-03 21:00:58 +00002956static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2957 LookupResult &Previous) {
2958 // C11 6.2.7p4:
2959 // For an identifier with internal or external linkage declared
2960 // in a scope in which a prior declaration of that identifier is
2961 // visible, if the prior declaration specifies internal or
2962 // external linkage, the type of the identifier at the later
2963 // declaration becomes the composite type.
2964 //
2965 // If the variable isn't visible, we do not merge with its type.
2966 if (Previous.isShadowed())
2967 return false;
2968
2969 if (S.getLangOpts().CPlusPlus) {
2970 // C++11 [dcl.array]p3:
2971 // If there is a preceding declaration of the entity in the same
2972 // scope in which the bound was specified, an omitted array bound
2973 // is taken to be the same as in that earlier declaration.
2974 return NewVD->isPreviousDeclInSameBlockScope() ||
2975 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2976 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2977 } else {
2978 // If the old declaration was function-local, don't merge with its
2979 // type unless we're in the same function.
2980 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2981 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2982 }
2983}
2984
Chris Lattner01564d92007-01-27 19:27:06 +00002985/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2986/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2987/// situation, merging decls or emitting diagnostics as appropriate.
2988///
Mike Stump11289f42009-09-09 15:08:12 +00002989/// Tentative definition rules (C99 6.9.2p2) are checked by
2990/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002991/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002992///
Richard Smith3c785782013-09-03 21:00:58 +00002993void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00002994 // If the new decl is already invalid, don't do any other checking.
2995 if (New->isInvalidDecl())
2996 return;
Mike Stump11289f42009-09-09 15:08:12 +00002997
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002998 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00002999 VarDecl *Old = 0;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003000 if (Previous.isSingleResult() &&
3001 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003002 if (New->getDescribedVarTemplate())
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003003 Old = Old->getDescribedVarTemplate() ? Old : 0;
3004 else
3005 Old = Old->getDescribedVarTemplate() ? 0 : Old;
3006 }
3007 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003008 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003009 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00003010 Diag(Previous.getRepresentativeDecl()->getLocation(),
3011 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003012 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00003013 }
Chris Lattner84966392008-03-03 03:28:21 +00003014
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00003015 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3016 return;
3017
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003018 // C++ [class.mem]p1:
3019 // A member shall not be declared twice in the member-specification [...]
3020 //
3021 // Here, we need only consider static data members.
3022 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3023 Diag(New->getLocation(), diag::err_duplicate_member)
3024 << New->getIdentifier();
3025 Diag(Old->getLocation(), diag::note_previous_declaration);
3026 New->setInvalidDecl();
3027 }
3028
Douglas Gregor32c17572012-01-01 20:30:41 +00003029 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003030 // Warn if an already-declared variable is made a weak_import in a subsequent
3031 // declaration
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003032 if (New->getAttr<WeakImportAttr>() &&
3033 Old->getStorageClass() == SC_None &&
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003034 !Old->getAttr<WeakImportAttr>()) {
3035 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3036 Diag(Old->getLocation(), diag::note_previous_definition);
3037 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003038 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003039 }
Chris Lattner84966392008-03-03 03:28:21 +00003040
Richard Smith30482bc2011-02-20 03:19:35 +00003041 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003042 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3043
Richard Smith30482bc2011-02-20 03:19:35 +00003044 if (New->isInvalidDecl())
3045 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003046
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003047 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003048 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003049 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003050 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003051 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003052 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003053 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003054 }
Mike Stump11289f42009-09-09 15:08:12 +00003055 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003056 // For an identifier declared with the storage-class specifier
3057 // extern in a scope in which a prior declaration of that
3058 // identifier is visible,23) if the prior declaration specifies
3059 // internal or external linkage, the linkage of the identifier at
3060 // the later declaration is the same as the linkage specified at
3061 // the prior declaration. If no prior declaration is visible, or
3062 // if the prior declaration specifies no linkage, then the
3063 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003064 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003065 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003066 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003067 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003068 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003069 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003070 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003071 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003072 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003073
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003074 // Check if extern is followed by non-extern and vice-versa.
3075 if (New->hasExternalStorage() &&
3076 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3077 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3078 Diag(Old->getLocation(), diag::note_previous_definition);
3079 return New->setInvalidDecl();
3080 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003081 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3082 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003083 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3084 Diag(Old->getLocation(), diag::note_previous_definition);
3085 return New->setInvalidDecl();
3086 }
3087
Steve Naroffa5629372008-09-17 14:05:40 +00003088 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003089
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003090 // FIXME: The test for external storage here seems wrong? We still
3091 // need to check for mismatches.
3092 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003093 // Don't complain about out-of-line definitions of static members.
3094 !(Old->getLexicalDeclContext()->isRecord() &&
3095 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003096 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003097 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003098 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003099 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003100
Richard Smithfd3834f2013-04-13 02:43:54 +00003101 if (New->getTLSKind() != Old->getTLSKind()) {
3102 if (!Old->getTLSKind()) {
3103 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3104 Diag(Old->getLocation(), diag::note_previous_declaration);
3105 } else if (!New->getTLSKind()) {
3106 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3107 Diag(Old->getLocation(), diag::note_previous_declaration);
3108 } else {
3109 // Do not allow redeclaration to change the variable between requiring
3110 // static and dynamic initialization.
3111 // FIXME: GCC allows this, but uses the TLS keyword on the first
3112 // declaration to determine the kind. Do we need to be compatible here?
3113 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3114 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3115 Diag(Old->getLocation(), diag::note_previous_declaration);
3116 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003117 }
3118
Sebastian Redlf1842912010-02-02 18:35:11 +00003119 // C++ doesn't have tentative definitions, so go right ahead and check here.
3120 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003121 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003122 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003123 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003124 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003125 Diag(Def->getLocation(), diag::note_previous_definition);
3126 New->setInvalidDecl();
3127 return;
3128 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003129
Rafael Espindolaf4187652013-02-14 01:18:37 +00003130 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003131 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3132 Diag(Old->getLocation(), diag::note_previous_definition);
3133 New->setInvalidDecl();
3134 return;
3135 }
3136
Rafael Espindolabefe1302012-11-25 14:07:59 +00003137 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003138 if (Old->getMostRecentDecl()->isUsed(false))
3139 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003140
Douglas Gregor0760fa12009-03-10 23:43:53 +00003141 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003142 New->setPreviousDecl(Old);
John McCall401982f2010-01-20 21:53:11 +00003143
3144 // Inherit access appropriately.
3145 New->setAccess(Old->getAccess());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003146
3147 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3148 if (New->isStaticDataMember() && New->isOutOfLine())
3149 VTD->setAccess(New->getAccess());
3150 }
Chris Lattner01564d92007-01-27 19:27:06 +00003151}
3152
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003153/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3154/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003155Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003156 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003157 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003158}
3159
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003160static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003161 if (!S.Context.getLangOpts().CPlusPlus)
3162 return;
3163
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003164 if (isa<CXXRecordDecl>(Tag->getParent())) {
3165 // If this tag is the direct child of a class, number it if
3166 // it is anonymous.
3167 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3168 return;
3169 MangleNumberingContext &MCtx =
3170 S.Context.getManglingNumberContext(Tag->getParent());
3171 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3172 return;
3173 }
3174
3175 // If this tag isn't a direct child of a class, number it if it is local.
3176 Decl *ManglingContextDecl;
3177 if (MangleNumberingContext *MCtx =
3178 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3179 ManglingContextDecl)) {
3180 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3181 }
3182}
3183
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003184/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003185/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003186/// parameters to cope with template friend declarations.
3187Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3188 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003189 MultiTemplateParamsArg TemplateParams,
3190 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003191 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003192 TagDecl *Tag = 0;
3193 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3194 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003195 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003196 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003197 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003198 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003199
3200 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003201 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003202
John McCall07e91c02009-08-06 02:15:43 +00003203 // Note that the above type specs guarantee that the
3204 // type rep is a Decl, whereas in many of the others
3205 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003206 if (isa<TagDecl>(TagD))
3207 Tag = cast<TagDecl>(TagD);
3208 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3209 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003210 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003211
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003212 if (Tag) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003213 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003214 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003215 if (Tag->isInvalidDecl())
3216 return Tag;
3217 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003218
Nuno Lopese9823fa2009-12-17 11:35:26 +00003219 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3220 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3221 // or incomplete types shall not be restrict-qualified."
3222 if (TypeQuals & DeclSpec::TQ_restrict)
3223 Diag(DS.getRestrictSpecLoc(),
3224 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3225 << DS.getSourceRange();
3226 }
3227
Richard Smitha77a0a62011-08-15 21:04:07 +00003228 if (DS.isConstexprSpecified()) {
3229 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3230 // and definitions of functions and variables.
3231 if (Tag)
3232 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3233 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3234 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003235 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3236 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003237 else
3238 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3239 // Don't emit warnings after this error.
3240 return TagD;
3241 }
3242
Richard Smithb1402ae2013-03-18 22:52:47 +00003243 DiagnoseFunctionSpecifiers(DS);
3244
Douglas Gregor3dad8422009-09-26 06:47:28 +00003245 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003246 // If we're dealing with a decl but not a TagDecl, assume that
3247 // whatever routines created it handled the friendship aspect.
3248 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003249 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003250 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003251 }
John McCallaa017372011-03-22 23:00:04 +00003252
Richard Smithb1402ae2013-03-18 22:52:47 +00003253 CXXScopeSpec &SS = DS.getTypeSpecScope();
3254 bool IsExplicitSpecialization =
3255 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3256 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3257 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3258 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3259 // nested-name-specifier unless it is an explicit instantiation
3260 // or an explicit specialization.
3261 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3262 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3263 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3264 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3265 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3266 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3267 << SS.getRange();
3268 return 0;
3269 }
3270
3271 // Track whether this decl-specifier declares anything.
3272 bool DeclaresAnything = true;
3273
3274 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003275 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003276 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003277 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003278 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003279 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00003280 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003281
Richard Smithb1402ae2013-03-18 22:52:47 +00003282 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003283 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003284 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003285
Richard Smithb1402ae2013-03-18 22:52:47 +00003286 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003287 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003288 CurContext->isRecord() &&
3289 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3290 // Handle 2 kinds of anonymous struct:
3291 // struct STRUCT;
3292 // and
3293 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3294 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003295 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003296 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3297 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003298 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003299 << DS.getSourceRange();
3300 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3301 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003302 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003303
3304 // Skip all the checks below if we have a type error.
3305 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3306 (TagD && TagD->isInvalidDecl()))
3307 return TagD;
3308
3309 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003310 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3311 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3312 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003313 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3314 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003315
John McCallaa017372011-03-22 23:00:04 +00003316 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003317 // Customize diagnostic for a typedef missing a name.
3318 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003319 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003320 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003321 else
3322 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003323 }
Mike Stump11289f42009-09-09 15:08:12 +00003324
Richard Smithb1402ae2013-03-18 22:52:47 +00003325 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003326 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3327 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3328 << Tag->getTagKind()
3329 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3330
Richard Smithb1402ae2013-03-18 22:52:47 +00003331 ActOnDocumentableDecl(TagD);
3332
3333 // C 6.7/2:
3334 // A declaration [...] shall declare at least a declarator [...], a tag,
3335 // or the members of an enumeration.
3336 // C++ [dcl.dcl]p3:
3337 // [If there are no declarators], and except for the declaration of an
3338 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3339 // names into the program, or shall redeclare a name introduced by a
3340 // previous declaration.
3341 if (!DeclaresAnything) {
3342 // In C, we allow this as a (popular) extension / bug. Don't bother
3343 // producing further diagnostics for redundant qualifiers after this.
3344 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3345 return TagD;
3346 }
3347
3348 // C++ [dcl.stc]p1:
3349 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3350 // init-declarator-list of the declaration shall not be empty.
3351 // C++ [dcl.fct.spec]p1:
3352 // If a cv-qualifier appears in a decl-specifier-seq, the
3353 // init-declarator-list of the declaration shall not be empty.
3354 //
3355 // Spurious qualifiers here appear to be valid in C.
3356 unsigned DiagID = diag::warn_standalone_specifier;
3357 if (getLangOpts().CPlusPlus)
3358 DiagID = diag::ext_standalone_specifier;
3359
3360 // Note that a linkage-specification sets a storage class, but
3361 // 'extern "C" struct foo;' is actually valid and not theoretically
3362 // useless.
3363 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3364 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3365 Diag(DS.getStorageClassSpecLoc(), DiagID)
3366 << DeclSpec::getSpecifierName(SCS);
3367
Richard Smithb4a9e862013-04-12 22:46:28 +00003368 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3369 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3370 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003371 if (DS.getTypeQualifiers()) {
3372 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3373 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3374 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3375 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3376 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003377 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3378 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003379 }
3380
Eli Friedmane3217952011-12-17 00:36:09 +00003381 // Warn about ignored type attributes, for example:
3382 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003383 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003384 if (!DS.getAttributes().empty()) {
3385 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3386 if (TypeSpecType == DeclSpec::TST_class ||
3387 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003388 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003389 TypeSpecType == DeclSpec::TST_union ||
3390 TypeSpecType == DeclSpec::TST_enum) {
3391 AttributeList* attrs = DS.getAttributes().getList();
3392 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003393 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003394 << attrs->getName()
3395 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3396 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003397 TypeSpecType == DeclSpec::TST_union ? 2 :
3398 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003399 attrs = attrs->getNext();
3400 }
3401 }
3402 }
John McCallaa017372011-03-22 23:00:04 +00003403
John McCall48871652010-08-21 09:40:31 +00003404 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003405}
3406
John McCallea305ed2009-12-18 10:40:03 +00003407/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003408/// check if there's an existing declaration that can't be overloaded.
3409///
3410/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003411static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3412 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003413 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003414 DeclarationName Name,
3415 SourceLocation NameLoc,
3416 unsigned diagnostic) {
3417 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3418 Sema::ForRedeclaration);
3419 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003420
John McCallea305ed2009-12-18 10:40:03 +00003421 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003422 return false;
3423
3424 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003425 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003426 assert(PrevDecl && "Expected a non-null Decl");
3427
3428 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3429 return false;
John McCall1f82f242009-11-18 22:49:29 +00003430
John McCallea305ed2009-12-18 10:40:03 +00003431 SemaRef.Diag(NameLoc, diagnostic) << Name;
3432 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003433
3434 return true;
3435}
3436
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003437/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3438/// anonymous struct or union AnonRecord into the owning context Owner
3439/// and scope S. This routine will be invoked just after we realize
3440/// that an unnamed union or struct is actually an anonymous union or
3441/// struct, e.g.,
3442///
3443/// @code
3444/// union {
3445/// int i;
3446/// float f;
3447/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3448/// // f into the surrounding scope.x
3449/// @endcode
3450///
3451/// This routine is recursive, injecting the names of nested anonymous
3452/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003453static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003454 DeclContext *Owner,
3455 RecordDecl *AnonRecord,
3456 AccessSpecifier AS,
3457 SmallVectorImpl<NamedDecl *> &Chaining,
3458 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003459 unsigned diagKind
3460 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3461 : diag::err_anonymous_struct_member_redecl;
3462
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003463 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003464
3465 // Look every FieldDecl and IndirectFieldDecl with a name.
3466 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3467 DEnd = AnonRecord->decls_end();
3468 D != DEnd; ++D) {
3469 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3470 cast<NamedDecl>(*D)->getDeclName()) {
3471 ValueDecl *VD = cast<ValueDecl>(*D);
3472 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3473 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003474 // C++ [class.union]p2:
3475 // The names of the members of an anonymous union shall be
3476 // distinct from the names of any other entity in the
3477 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003478 Invalid = true;
3479 } else {
3480 // C++ [class.union]p2:
3481 // For the purpose of name lookup, after the anonymous union
3482 // definition, the members of the anonymous union are
3483 // considered to have been defined in the scope in which the
3484 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003485 unsigned OldChainingSize = Chaining.size();
3486 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3487 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3488 PE = IF->chain_end(); PI != PE; ++PI)
3489 Chaining.push_back(*PI);
3490 else
3491 Chaining.push_back(VD);
3492
Francois Pichet783dd6e2010-11-21 06:08:52 +00003493 assert(Chaining.size() >= 2);
3494 NamedDecl **NamedChain =
3495 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3496 for (unsigned i = 0; i < Chaining.size(); i++)
3497 NamedChain[i] = Chaining[i];
3498
3499 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003500 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3501 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003502 NamedChain, Chaining.size());
3503
3504 IndirectField->setAccess(AS);
3505 IndirectField->setImplicit();
3506 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003507
3508 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003509 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003510
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003511 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003512 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003513 }
3514 }
3515
3516 return Invalid;
3517}
3518
Douglas Gregorc4df4072010-04-19 22:54:31 +00003519/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3520/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003521/// illegal input values are mapped to SC_None.
3522static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003523StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3524 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3525 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3526 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003527 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003528 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003529 case DeclSpec::SCS_extern:
3530 if (DS.isExternInLinkageSpec())
3531 return SC_None;
3532 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003533 case DeclSpec::SCS_static: return SC_Static;
3534 case DeclSpec::SCS_auto: return SC_Auto;
3535 case DeclSpec::SCS_register: return SC_Register;
3536 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003537 // Illegal SCSs map to None: error reporting is up to the caller.
3538 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003539 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003540 }
3541 llvm_unreachable("unknown storage class specifier");
3542}
3543
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003544/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003545/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003546/// (C++ [class.union]) and a C11 feature; anonymous structures
3547/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003548Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3549 AccessSpecifier AS,
3550 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003551 DeclContext *Owner = Record->getDeclContext();
3552
3553 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003554 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003555 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003556 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003557 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003558 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003559 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003560
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003561 // C and C++ require different kinds of checks for anonymous
3562 // structs/unions.
3563 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003564 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003565 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003566 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003567 if (Record->isUnion()) {
3568 // C++ [class.union]p6:
3569 // Anonymous unions declared in a named namespace or in the
3570 // global namespace shall be declared static.
3571 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3572 (isa<TranslationUnitDecl>(Owner) ||
3573 (isa<NamespaceDecl>(Owner) &&
3574 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003575 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3576 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003577
3578 // Recover by adding 'static'.
3579 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3580 PrevSpec, DiagID);
3581 }
3582 // C++ [class.union]p6:
3583 // A storage class is not allowed in a declaration of an
3584 // anonymous union in a class scope.
3585 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3586 isa<RecordDecl>(Owner)) {
3587 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003588 diag::err_anonymous_union_with_storage_spec)
3589 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003590
3591 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003592 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3593 SourceLocation(),
David Blaikie0a8e8992011-10-19 22:43:29 +00003594 PrevSpec, DiagID);
3595 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003596 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003597
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003598 // Ignore const/volatile/restrict qualifiers.
3599 if (DS.getTypeQualifiers()) {
3600 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3601 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003602 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003603 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3604 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003605 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003606 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003607 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003608 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3609 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003610 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003611 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003612 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003613 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003614 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3615 Diag(DS.getAtomicSpecLoc(),
3616 diag::ext_anonymous_struct_union_qualified)
3617 << Record->isUnion() << "_Atomic"
3618 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003619
3620 DS.ClearTypeQualifiers();
3621 }
3622
Mike Stump11289f42009-09-09 15:08:12 +00003623 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003624 // The member-specification of an anonymous union shall only
3625 // define non-static data members. [Note: nested types and
3626 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003627 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3628 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003629 Mem != MemEnd; ++Mem) {
3630 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3631 // C++ [class.union]p3:
3632 // An anonymous union shall not have private or protected
3633 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003634 assert(FD->getAccess() != AS_none);
3635 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003636 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3637 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3638 Invalid = true;
3639 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003640
Alexis Hunt97ab5542011-05-16 22:41:40 +00003641 // C++ [class.union]p1
3642 // An object of a class with a non-trivial constructor, a non-trivial
3643 // copy constructor, a non-trivial destructor, or a non-trivial copy
3644 // assignment operator cannot be a member of a union, nor can an
3645 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003646 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003647 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00003648 } else if ((*Mem)->isImplicit()) {
3649 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00003650 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3651 // This is a type that showed up in an
3652 // elaborated-type-specifier inside the anonymous struct or
3653 // union, but which actually declares a type outside of the
3654 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003655 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3656 if (!MemRecord->isAnonymousStructOrUnion() &&
3657 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003658 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003659 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003660 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3661 << (int)Record->isUnion();
3662 else {
3663 // This is a nested type declaration.
3664 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3665 << (int)Record->isUnion();
3666 Invalid = true;
3667 }
Richard Smith254d2662013-01-28 00:54:05 +00003668 } else {
3669 // This is an anonymous type definition within another anonymous type.
3670 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3671 // not part of standard C++.
3672 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003673 diag::ext_anonymous_record_with_anonymous_type)
3674 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003675 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00003676 } else if (isa<AccessSpecDecl>(*Mem)) {
3677 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003678 } else {
3679 // We have something that isn't a non-static data
3680 // member. Complain about it.
3681 unsigned DK = diag::err_anonymous_record_bad_member;
3682 if (isa<TypeDecl>(*Mem))
3683 DK = diag::err_anonymous_record_with_type;
3684 else if (isa<FunctionDecl>(*Mem))
3685 DK = diag::err_anonymous_record_with_function;
3686 else if (isa<VarDecl>(*Mem))
3687 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003688
3689 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003690 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003691 DK == diag::err_anonymous_record_with_type)
3692 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003693 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003694 else {
3695 Diag((*Mem)->getLocation(), DK)
3696 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003697 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003698 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003699 }
3700 }
Mike Stump11289f42009-09-09 15:08:12 +00003701 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003702
3703 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003704 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003705 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003706 Invalid = true;
3707 }
3708
John McCallfa2d6922009-10-22 23:31:08 +00003709 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003710 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003711 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003712 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003713
Mike Stump11289f42009-09-09 15:08:12 +00003714 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003715 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003716 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003717 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003718 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003719 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003720 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003721 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003722 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003723 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003724 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003725 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003726 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003727 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003728 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003729 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003730 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003731 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003732 // mutable can only appear on non-static class members, so it's always
3733 // an error here
3734 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3735 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003736 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003737 }
3738
Abramo Bagnaradff19302011-03-08 08:55:46 +00003739 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003740 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003741 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003742 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003743 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003744
3745 // Default-initialize the implicit variable. This initialization will be
3746 // trivial in almost all cases, except if a union member has an in-class
3747 // initializer:
3748 // union { int n = 0; };
3749 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003750 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003751 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003752
3753 // Add the anonymous struct/union object to the current
3754 // context. We'll be referencing this object when we refer to one of
3755 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003756 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00003757
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003758 // Inject the members of the anonymous struct/union into the owning
3759 // context and into the identifier resolver chain for name lookup
3760 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003761 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003762 Chain.push_back(Anon);
3763
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003764 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3765 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003766 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003767
3768 // Mark this as an anonymous struct/union type. Note that we do not
3769 // do this until after we have already checked and injected the
3770 // members of this anonymous struct/union type, because otherwise
3771 // the members could be injected twice: once by DeclContext when it
3772 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00003773 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003774 Record->setAnonymousStructOrUnion(true);
3775
3776 if (Invalid)
3777 Anon->setInvalidDecl();
3778
John McCall48871652010-08-21 09:40:31 +00003779 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003780}
3781
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003782/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3783/// Microsoft C anonymous structure.
3784/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3785/// Example:
3786///
3787/// struct A { int a; };
3788/// struct B { struct A; int b; };
3789///
3790/// void foo() {
3791/// B var;
3792/// var.a = 3;
3793/// }
3794///
3795Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3796 RecordDecl *Record) {
3797
3798 // If there is no Record, get the record via the typedef.
3799 if (!Record)
3800 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3801
3802 // Mock up a declarator.
3803 Declarator Dc(DS, Declarator::TypeNameContext);
3804 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3805 assert(TInfo && "couldn't build declarator info for anonymous struct");
3806
3807 // Create a declaration for this anonymous struct.
3808 NamedDecl* Anon = FieldDecl::Create(Context,
3809 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003810 DS.getLocStart(),
3811 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003812 /*IdentifierInfo=*/0,
3813 Context.getTypeDeclType(Record),
3814 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003815 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003816 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003817 Anon->setImplicit();
3818
3819 // Add the anonymous struct object to the current context.
3820 CurContext->addDecl(Anon);
3821
3822 // Inject the members of the anonymous struct into the current
3823 // context and into the identifier resolver chain for name lookup
3824 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003825 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003826 Chain.push_back(Anon);
3827
Nico Weberf8bb3de2012-02-01 00:41:00 +00003828 RecordDecl *RecordDef = Record->getDefinition();
3829 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3830 RecordDef, AS_none,
3831 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003832 Anon->setInvalidDecl();
3833
3834 return Anon;
3835}
Steve Naroff2fea1392007-09-02 02:04:30 +00003836
Douglas Gregor92751d42008-11-17 22:58:34 +00003837/// GetNameForDeclarator - Determine the full declaration name for the
3838/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003839DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003840 return GetNameFromUnqualifiedId(D.getName());
3841}
3842
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003843/// \brief Retrieves the declaration name from a parsed unqualified-id.
3844DeclarationNameInfo
3845Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3846 DeclarationNameInfo NameInfo;
3847 NameInfo.setLoc(Name.StartLocation);
3848
Douglas Gregor7861a802009-11-03 01:35:08 +00003849 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003850
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003851 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003852 case UnqualifiedId::IK_Identifier:
3853 NameInfo.setName(Name.Identifier);
3854 NameInfo.setLoc(Name.StartLocation);
3855 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003856
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003857 case UnqualifiedId::IK_OperatorFunctionId:
3858 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3859 Name.OperatorFunctionId.Operator));
3860 NameInfo.setLoc(Name.StartLocation);
3861 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3862 = Name.OperatorFunctionId.SymbolLocations[0];
3863 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3864 = Name.EndLocation.getRawEncoding();
3865 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003866
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003867 case UnqualifiedId::IK_LiteralOperatorId:
3868 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3869 Name.Identifier));
3870 NameInfo.setLoc(Name.StartLocation);
3871 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3872 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003873
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003874 case UnqualifiedId::IK_ConversionFunctionId: {
3875 TypeSourceInfo *TInfo;
3876 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3877 if (Ty.isNull())
3878 return DeclarationNameInfo();
3879 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3880 Context.getCanonicalType(Ty)));
3881 NameInfo.setLoc(Name.StartLocation);
3882 NameInfo.setNamedTypeInfo(TInfo);
3883 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003884 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003885
3886 case UnqualifiedId::IK_ConstructorName: {
3887 TypeSourceInfo *TInfo;
3888 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3889 if (Ty.isNull())
3890 return DeclarationNameInfo();
3891 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3892 Context.getCanonicalType(Ty)));
3893 NameInfo.setLoc(Name.StartLocation);
3894 NameInfo.setNamedTypeInfo(TInfo);
3895 return NameInfo;
3896 }
3897
3898 case UnqualifiedId::IK_ConstructorTemplateId: {
3899 // In well-formed code, we can only have a constructor
3900 // template-id that refers to the current context, so go there
3901 // to find the actual type being constructed.
3902 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3903 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3904 return DeclarationNameInfo();
3905
3906 // Determine the type of the class being constructed.
3907 QualType CurClassType = Context.getTypeDeclType(CurClass);
3908
3909 // FIXME: Check two things: that the template-id names the same type as
3910 // CurClassType, and that the template-id does not occur when the name
3911 // was qualified.
3912
3913 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3914 Context.getCanonicalType(CurClassType)));
3915 NameInfo.setLoc(Name.StartLocation);
3916 // FIXME: should we retrieve TypeSourceInfo?
3917 NameInfo.setNamedTypeInfo(0);
3918 return NameInfo;
3919 }
3920
3921 case UnqualifiedId::IK_DestructorName: {
3922 TypeSourceInfo *TInfo;
3923 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3924 if (Ty.isNull())
3925 return DeclarationNameInfo();
3926 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3927 Context.getCanonicalType(Ty)));
3928 NameInfo.setLoc(Name.StartLocation);
3929 NameInfo.setNamedTypeInfo(TInfo);
3930 return NameInfo;
3931 }
3932
3933 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003934 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003935 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3936 return Context.getNameForTemplate(TName, TNameLoc);
3937 }
3938
3939 } // switch (Name.getKind())
3940
David Blaikie83d382b2011-09-23 05:06:16 +00003941 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003942}
3943
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003944static QualType getCoreType(QualType Ty) {
3945 do {
3946 if (Ty->isPointerType() || Ty->isReferenceType())
3947 Ty = Ty->getPointeeType();
3948 else if (Ty->isArrayType())
3949 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3950 else
3951 return Ty.withoutLocalFastQualifiers();
3952 } while (true);
3953}
3954
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003955/// hasSimilarParameters - Determine whether the C++ functions Declaration
3956/// and Definition have "nearly" matching parameters. This heuristic is
3957/// used to improve diagnostics in the case where an out-of-line function
3958/// definition doesn't match any declaration within the class or namespace.
3959/// Also sets Params to the list of indices to the parameters that differ
3960/// between the declaration and the definition. If hasSimilarParameters
3961/// returns true and Params is empty, then all of the parameters match.
3962static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003963 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003964 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003965 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003966 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003967 if (Declaration->param_size() != Definition->param_size())
3968 return false;
3969 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3970 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3971 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3972
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003973 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00003974 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003975 continue;
3976
3977 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3978 QualType DefParamBaseTy = getCoreType(DefParamTy);
3979 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3980 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3981
3982 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3983 (DeclTyName && DeclTyName == DefTyName))
3984 Params.push_back(Idx);
3985 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00003986 return false;
3987 }
3988
3989 return true;
3990}
3991
John McCall99b2fe52010-04-29 23:50:39 +00003992/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3993/// declarator needs to be rebuilt in the current instantiation.
3994/// Any bits of declarator which appear before the name are valid for
3995/// consideration here. That's specifically the type in the decl spec
3996/// and the base type in any member-pointer chunks.
3997static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3998 DeclarationName Name) {
3999 // The types we specifically need to rebuild are:
4000 // - typenames, typeofs, and decltypes
4001 // - types which will become injected class names
4002 // Of course, we also need to rebuild any type referencing such a
4003 // type. It's safest to just say "dependent", but we call out a
4004 // few cases here.
4005
4006 DeclSpec &DS = D.getMutableDeclSpec();
4007 switch (DS.getTypeSpecType()) {
4008 case DeclSpec::TST_typename:
4009 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004010 case DeclSpec::TST_underlyingType:
4011 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004012 // Grab the type from the parser.
4013 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004014 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004015 if (T.isNull() || !T->isDependentType()) break;
4016
4017 // Make sure there's a type source info. This isn't really much
4018 // of a waste; most dependent types should have type source info
4019 // attached already.
4020 if (!TSI)
4021 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4022
4023 // Rebuild the type in the current instantiation.
4024 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4025 if (!TSI) return true;
4026
4027 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004028 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4029 DS.UpdateTypeRep(LocType);
4030 break;
4031 }
4032
Richard Smith1620ebd2012-10-01 20:35:07 +00004033 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004034 case DeclSpec::TST_typeofExpr: {
4035 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004036 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004037 if (Result.isInvalid()) return true;
4038 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004039 break;
4040 }
4041
4042 default:
4043 // Nothing to do for these decl specs.
4044 break;
4045 }
4046
4047 // It doesn't matter what order we do this in.
4048 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4049 DeclaratorChunk &Chunk = D.getTypeObject(I);
4050
4051 // The only type information in the declarator which can come
4052 // before the declaration name is the base type of a member
4053 // pointer.
4054 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4055 continue;
4056
4057 // Rebuild the scope specifier in-place.
4058 CXXScopeSpec &SS = Chunk.Mem.Scope();
4059 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4060 return true;
4061 }
4062
4063 return false;
4064}
4065
Anders Carlsson1052fd72011-07-04 16:28:17 +00004066Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004067 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004068 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004069
4070 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004071 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004072 Dcl->setTopLevelDeclInObjCContainer();
4073
4074 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004075}
4076
Richard Smithdda56e42011-04-15 14:24:37 +00004077/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4078/// If T is the name of a class, then each of the following shall have a
4079/// name different from T:
4080/// - every static data member of class T;
4081/// - every member function of class T
4082/// - every member of class T that is itself a type;
4083/// \returns true if the declaration name violates these rules.
4084bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4085 DeclarationNameInfo NameInfo) {
4086 DeclarationName Name = NameInfo.getName();
4087
4088 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4089 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4090 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4091 return true;
4092 }
4093
4094 return false;
4095}
Douglas Gregor31feb332012-03-17 23:06:31 +00004096
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004097/// \brief Diagnose a declaration whose declarator-id has the given
4098/// nested-name-specifier.
4099///
4100/// \param SS The nested-name-specifier of the declarator-id.
4101///
4102/// \param DC The declaration context to which the nested-name-specifier
4103/// resolves.
4104///
4105/// \param Name The name of the entity being declared.
4106///
4107/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004108///
4109/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004110bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004111 DeclarationName Name,
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004112 SourceLocation Loc) {
4113 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004114 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004115 Cur = Cur->getParent();
4116
4117 // C++ [dcl.meaning]p1:
4118 // A declarator-id shall not be qualified except for the definition
4119 // of a member function (9.3) or static data member (9.4) outside of
4120 // its class, the definition or explicit instantiation of a function
4121 // or variable member of a namespace outside of its namespace, or the
4122 // definition of an explicit specialization outside of its namespace,
4123 // or the declaration of a friend function that is a member of
4124 // another class or namespace (11.3). [...]
4125
4126 // The user provided a superfluous scope specifier that refers back to the
4127 // class or namespaces in which the entity is already declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004128 //
4129 // class X {
4130 // void X::f();
4131 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004132 if (Cur->Equals(DC)) {
Douglas Gregor43bc0362012-09-13 20:16:20 +00004133 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4134 : diag::err_member_extra_qualification)
Douglas Gregor31feb332012-03-17 23:06:31 +00004135 << Name << FixItHint::CreateRemoval(SS.getRange());
4136 SS.clear();
4137 return false;
4138 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004139
4140 // Check whether the qualifying scope encloses the scope of the original
4141 // declaration.
4142 if (!Cur->Encloses(DC)) {
4143 if (Cur->isRecord())
4144 Diag(Loc, diag::err_member_qualification)
4145 << Name << SS.getRange();
4146 else if (isa<TranslationUnitDecl>(DC))
4147 Diag(Loc, diag::err_invalid_declarator_global_scope)
4148 << Name << SS.getRange();
4149 else if (isa<FunctionDecl>(Cur))
4150 Diag(Loc, diag::err_invalid_declarator_in_function)
4151 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004152 else if (isa<BlockDecl>(Cur))
4153 Diag(Loc, diag::err_invalid_declarator_in_block)
4154 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004155 else
4156 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004157 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004158
Douglas Gregor31feb332012-03-17 23:06:31 +00004159 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004160 }
4161
4162 if (Cur->isRecord()) {
4163 // Cannot qualify members within a class.
4164 Diag(Loc, diag::err_member_qualification)
4165 << Name << SS.getRange();
4166 SS.clear();
4167
4168 // C++ constructors and destructors with incorrect scopes can break
4169 // our AST invariants by having the wrong underlying types. If
4170 // that's the case, then drop this declaration entirely.
4171 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4172 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4173 !Context.hasSameType(Name.getCXXNameType(),
4174 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4175 return true;
4176
4177 return false;
4178 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004179
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004180 // C++11 [dcl.meaning]p1:
4181 // [...] "The nested-name-specifier of the qualified declarator-id shall
4182 // not begin with a decltype-specifer"
4183 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4184 while (SpecLoc.getPrefix())
4185 SpecLoc = SpecLoc.getPrefix();
4186 if (dyn_cast_or_null<DecltypeType>(
4187 SpecLoc.getNestedNameSpecifier()->getAsType()))
4188 Diag(Loc, diag::err_decltype_in_declarator)
4189 << SpecLoc.getTypeLoc().getSourceRange();
4190
Douglas Gregor31feb332012-03-17 23:06:31 +00004191 return false;
4192}
4193
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004194NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4195 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004196 // TODO: consider using NameInfo for diagnostic.
4197 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4198 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004199
Chris Lattner02c04392007-07-25 00:24:17 +00004200 // All of these full declarators require an identifier. If it doesn't have
4201 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004202 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004203 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004204 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004205 diag::err_declarator_need_ident)
4206 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004207 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004208 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4209 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004210
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004211 // The scope passed in may not be a decl scope. Zip up the scope tree until
4212 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004213 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004214 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004215 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004216
John McCall99b2fe52010-04-29 23:50:39 +00004217 DeclContext *DC = CurContext;
4218 if (D.getCXXScopeSpec().isInvalid())
4219 D.setInvalidType();
4220 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004221 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4222 UPPC_DeclarationQualifier))
4223 return 0;
4224
John McCall99b2fe52010-04-29 23:50:39 +00004225 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4226 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4227 if (!DC) {
4228 // If we could not compute the declaration context, it's because the
4229 // declaration context is dependent but does not refer to a class,
4230 // class template, or class template partial specialization. Complain
4231 // and return early, to avoid the coming semantic disaster.
4232 Diag(D.getIdentifierLoc(),
4233 diag::err_template_qualified_declarator_no_match)
4234 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4235 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004236 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004237 }
John McCall99b2fe52010-04-29 23:50:39 +00004238 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004239
John McCall99b2fe52010-04-29 23:50:39 +00004240 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004241 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004242 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004243
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004244 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4245 Diag(D.getIdentifierLoc(),
4246 diag::err_member_def_undefined_record)
4247 << Name << DC << D.getCXXScopeSpec().getRange();
4248 D.setInvalidType();
4249 } else if (!D.getDeclSpec().isFriendSpecified()) {
4250 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4251 Name, D.getIdentifierLoc())) {
4252 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004253 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004254
4255 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004256 }
John McCall99b2fe52010-04-29 23:50:39 +00004257 }
4258
4259 // Check whether we need to rebuild the type of the given
4260 // declaration in the current instantiation.
4261 if (EnteringContext && IsDependentContext &&
4262 TemplateParamLists.size() != 0) {
4263 ContextRAII SavedContext(*this, DC);
4264 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4265 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004266 }
4267 }
Richard Smithdda56e42011-04-15 14:24:37 +00004268
4269 if (DiagnoseClassNameShadow(DC, NameInfo))
4270 // If this is a typedef, we'll end up spewing multiple diagnostics.
4271 // Just return early; it's safer.
4272 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4273 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004274
John McCall8cb7bdf2010-06-04 23:28:52 +00004275 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4276 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004277
Douglas Gregor506bd562010-12-13 22:49:22 +00004278 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4279 UPPC_DeclarationType))
4280 D.setInvalidType();
4281
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004282 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004283 ForRedeclaration);
4284
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004285 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004286 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004287 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004288 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004289
4290 // If the declaration we're planning to build will be a function
4291 // or object with linkage, then look for another declaration with
4292 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004293 //
4294 // If the declaration we're planning to build will be declared with
4295 // external linkage in the translation unit, create any builtin with
4296 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004297 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4298 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004299 else if (CurContext->isFunctionOrMethod() &&
4300 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4301 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004302 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004303 CreateBuiltins =
4304 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4305 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4306 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4307 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004308
4309 if (IsLinkageLookup)
4310 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004311
Richard Smith1c34fb72013-08-13 18:18:50 +00004312 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004313 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004314 LookupQualifiedName(Previous, DC);
4315
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004316 // C++ [dcl.meaning]p1:
4317 // When the declarator-id is qualified, the declaration shall refer to a
4318 // previously declared member of the class or namespace to which the
4319 // qualifier refers (or, in the case of a namespace, of an element of the
4320 // inline namespace set of that namespace (7.3.1)) or to a specialization
4321 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004322 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004323 // Note that we already checked the context above, and that we do not have
4324 // enough information to make sure that Previous contains the declaration
4325 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004326 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004327 // class X {
4328 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004329 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004330 // };
4331 //
Douglas Gregorad590502008-12-15 23:53:10 +00004332 // void X::f(int) { } // ill-formed
4333 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004334 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004335 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004336 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004337
4338 // C++ [dcl.meaning]p1:
4339 // [...] the member shall not merely have been introduced by a
4340 // using-declaration in the scope of the class or namespace nominated by
4341 // the nested-name-specifier of the declarator-id.
4342 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004343 }
4344
John McCall1f82f242009-11-18 22:49:29 +00004345 if (Previous.isSingleResult() &&
4346 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004347 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004348 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004349 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4350 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004351
Douglas Gregor5101c242008-12-05 18:15:24 +00004352 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004353 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004354 }
4355
Douglas Gregor83a586e2008-04-13 21:07:44 +00004356 // In C++, the previous declaration we find might be a tag type
4357 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004358 // tag type. Note that this does does not apply if we're declaring a
4359 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004360 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00004361 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004362 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004363
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004364 // Check that there are no default arguments other than in the parameters
4365 // of a function declaration (C++ only).
4366 if (getLangOpts().CPlusPlus)
4367 CheckExtraCXXDefaultArguments(D);
4368
Nico Webercb4c7f42012-12-23 00:40:46 +00004369 NamedDecl *New;
4370
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004371 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004372 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004373 if (TemplateParamLists.size()) {
4374 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004375 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004376 }
Mike Stump11289f42009-09-09 15:08:12 +00004377
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004378 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004379 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004380 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004381 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004382 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004383 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004384 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4385 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004386 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004387
4388 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004389 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004390
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004391 // If this has an identifier and is not an invalid redeclaration or
4392 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004393 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004394 !(D.isRedeclaration() && New->isInvalidDecl())) {
4395 // Only make a locally-scoped extern declaration visible if it is the first
4396 // declaration of this entity. Qualified lookup for such an entity should
4397 // only find this declaration if there is no visible declaration of it.
4398 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4399 PushOnScopeChains(New, S, AddToContext);
4400 if (!AddToContext)
4401 CurContext->addHiddenDecl(New);
4402 }
Mike Stump11289f42009-09-09 15:08:12 +00004403
John McCall48871652010-08-21 09:40:31 +00004404 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004405}
4406
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004407/// Helper method to turn variable array types into constant array
4408/// types in certain situations which would otherwise be errors (for
4409/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004410static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4411 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004412 bool &SizeIsNegative,
4413 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004414 // This method tries to turn a variable array into a constant
4415 // array even when the size isn't an ICE. This is necessary
4416 // for compatibility with code that depends on gcc's buggy
4417 // constant expression folding, like struct {char x[(int)(char*)2];}
4418 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004419 Oversized = 0;
4420
4421 if (T->isDependentType())
4422 return QualType();
4423
John McCall8ccfcb52009-09-24 19:53:00 +00004424 QualifierCollector Qs;
4425 const Type *Ty = Qs.strip(T);
4426
4427 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004428 QualType Pointee = PTy->getPointeeType();
4429 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004430 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4431 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004432 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004433 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004434 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004435 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004436 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4437 QualType Inner = PTy->getInnerType();
4438 QualType FixedType =
4439 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4440 Oversized);
4441 if (FixedType.isNull()) return FixedType;
4442 FixedType = Context.getParenType(FixedType);
4443 return Qs.apply(Context, FixedType);
4444 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004445
4446 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004447 if (!VLATy)
4448 return QualType();
4449 // FIXME: We should probably handle this case
4450 if (VLATy->getElementType()->isVariablyModifiedType())
4451 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004452
Richard Smith42d3af92011-12-07 00:43:50 +00004453 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004454 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004455 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004456 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004457
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004458 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004459 if (Res.isSigned() && Res.isNegative()) {
4460 SizeIsNegative = true;
4461 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004462 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004463
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004464 // Check whether the array is too large to be addressed.
4465 unsigned ActiveSizeBits
4466 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4467 Res);
4468 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4469 Oversized = Res;
4470 return QualType();
4471 }
4472
4473 return Context.getConstantArrayType(VLATy->getElementType(),
4474 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004475}
4476
Abramo Bagnara341ab732012-11-08 14:44:42 +00004477static void
4478FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004479 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4480 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4481 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4482 DstPTL.getPointeeLoc());
4483 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004484 return;
4485 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004486 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4487 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4488 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4489 DstPTL.getInnerLoc());
4490 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4491 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004492 return;
4493 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004494 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4495 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4496 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4497 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004498 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004499 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4500 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4501 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004502}
4503
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004504/// Helper method to turn variable array types into constant array
4505/// types in certain situations which would otherwise be errors (for
4506/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004507static TypeSourceInfo*
4508TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4509 ASTContext &Context,
4510 bool &SizeIsNegative,
4511 llvm::APSInt &Oversized) {
4512 QualType FixedTy
4513 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4514 SizeIsNegative, Oversized);
4515 if (FixedTy.isNull())
4516 return 0;
4517 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4518 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4519 FixedTInfo->getTypeLoc());
4520 return FixedTInfo;
4521}
4522
Richard Smith78165b52013-01-10 23:43:47 +00004523/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004524/// that it can be found later for redeclarations. We include any extern "C"
4525/// declaration that is not visible in the translation unit here, not just
4526/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004527void
Richard Smith39b79682013-06-18 20:15:12 +00004528Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004529 if (!getLangOpts().CPlusPlus &&
4530 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4531 // Don't need to track declarations in the TU in C.
4532 return;
4533
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004534 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004535 // FIXME: There can be multiple such declarations if they are functions marked
4536 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004537 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004538}
4539
Richard Smith39b79682013-06-18 20:15:12 +00004540NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004541 if (ExternalSource) {
4542 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004543 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004544 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004545 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004546 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4547 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004548 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4549 if (Pos == LocallyScopedExternCDecls.end())
4550 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004551 }
4552 }
Richard Smith39b79682013-06-18 20:15:12 +00004553
4554 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004555 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004556}
4557
Eli Friedman574c7452009-04-07 19:37:57 +00004558/// \brief Diagnose function specifiers on a declaration of an identifier that
4559/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004560void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004561 // FIXME: We should probably indicate the identifier in question to avoid
4562 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004563 if (DS.isInlineSpecified())
4564 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004565 diag::err_inline_non_function);
4566
Richard Smithb1402ae2013-03-18 22:52:47 +00004567 if (DS.isVirtualSpecified())
4568 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004569 diag::err_virtual_non_function);
4570
Richard Smithb1402ae2013-03-18 22:52:47 +00004571 if (DS.isExplicitSpecified())
4572 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004573 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004574
Richard Smithb1402ae2013-03-18 22:52:47 +00004575 if (DS.isNoreturnSpecified())
4576 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004577 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004578}
4579
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004580NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004581Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004582 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004583 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4584 if (D.getCXXScopeSpec().isSet()) {
4585 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4586 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004587 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004588 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004589 DC = CurContext;
4590 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004591 }
4592
Richard Smithb1402ae2013-03-18 22:52:47 +00004593 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004594
Richard Smitha77a0a62011-08-15 21:04:07 +00004595 if (D.getDeclSpec().isConstexprSpecified())
4596 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4597 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004598
Douglas Gregord8f446f2010-07-13 06:37:01 +00004599 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4600 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4601 << D.getName().getSourceRange();
4602 return 0;
4603 }
4604
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004605 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004606 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004607
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004608 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004609 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004610
Richard Smith3f1b5d02011-05-05 21:57:07 +00004611 CheckTypedefForVariablyModifiedType(S, NewTD);
4612
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004613 bool Redeclaration = D.isRedeclaration();
4614 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4615 D.setRedeclaration(Redeclaration);
4616 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004617}
4618
Richard Smith3f1b5d02011-05-05 21:57:07 +00004619void
4620Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004621 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4622 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004623 // Note that variably modified types must be fixed before merging the decl so
4624 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004625 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4626 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004627 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004628 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004629
Chris Lattner9fecd742009-04-19 05:21:20 +00004630 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004631 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004632 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004633 TypeSourceInfo *FixedTInfo =
4634 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4635 SizeIsNegative,
4636 Oversized);
4637 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004638 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004639 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004640 } else {
4641 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004642 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004643 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004644 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004645 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004646 Diag(NewTD->getLocation(), diag::err_array_too_large)
4647 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004648 else
Richard Smithdda56e42011-04-15 14:24:37 +00004649 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004650 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004651 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004652 }
4653 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004654}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004655
Richard Smith3f1b5d02011-05-05 21:57:07 +00004656
4657/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4658/// declares a typedef-name, either using the 'typedef' type specifier or via
4659/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4660NamedDecl*
4661Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4662 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004663 // Merge the decl with the existing one if appropriate. If the decl is
4664 // in an outer scope, it isn't the same thing.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004665 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregordb446112011-03-07 16:54:27 +00004666 /*ExplicitInstantiationOrSpecialization=*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004667 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004668 if (!Previous.empty()) {
4669 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004670 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004671 }
4672
Douglas Gregor27821ce2009-07-07 16:35:42 +00004673 // If this is the C FILE type, notify the AST context.
4674 if (IdentifierInfo *II = NewTD->getIdentifier())
4675 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004676 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004677 if (II->isStr("FILE"))
4678 Context.setFILEDecl(NewTD);
4679 else if (II->isStr("jmp_buf"))
4680 Context.setjmp_bufDecl(NewTD);
4681 else if (II->isStr("sigjmp_buf"))
4682 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004683 else if (II->isStr("ucontext_t"))
4684 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004685 }
4686
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004687 return NewTD;
4688}
4689
Douglas Gregor5d68a202009-02-24 19:23:27 +00004690/// \brief Determines whether the given declaration is an out-of-scope
4691/// previous declaration.
4692///
4693/// This routine should be invoked when name lookup has found a
4694/// previous declaration (PrevDecl) that is not in the scope where a
4695/// new declaration by the same name is being introduced. If the new
4696/// declaration occurs in a local scope, previous declarations with
4697/// linkage may still be considered previous declarations (C99
4698/// 6.2.2p4-5, C++ [basic.link]p6).
4699///
4700/// \param PrevDecl the previous declaration found by name
4701/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004702///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004703/// \param DC the context in which the new declaration is being
4704/// declared.
4705///
4706/// \returns true if PrevDecl is an out-of-scope previous declaration
4707/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004708static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004709isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4710 ASTContext &Context) {
4711 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004712 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004713
Douglas Gregoreddf4332009-02-24 20:03:32 +00004714 if (!PrevDecl->hasLinkage())
4715 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004716
David Blaikiebbafb8a2012-03-11 07:00:24 +00004717 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004718 // C++ [basic.link]p6:
4719 // If there is a visible declaration of an entity with linkage
4720 // having the same name and type, ignoring entities declared
4721 // outside the innermost enclosing namespace scope, the block
4722 // scope declaration declares that same entity and receives the
4723 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004724 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004725 if (!OuterContext->isFunctionOrMethod())
4726 // This rule only applies to block-scope declarations.
4727 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004728
4729 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4730 if (PrevOuterContext->isRecord())
4731 // We found a member function: ignore it.
4732 return false;
4733
4734 // Find the innermost enclosing namespace for the new and
4735 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004736 OuterContext = OuterContext->getEnclosingNamespaceContext();
4737 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004738
Douglas Gregorfcee9462010-08-27 22:55:10 +00004739 // The previous declaration is in a different namespace, so it
4740 // isn't the same function.
4741 if (!OuterContext->Equals(PrevOuterContext))
4742 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004743 }
4744
Douglas Gregor5d68a202009-02-24 19:23:27 +00004745 return true;
4746}
4747
John McCall3e11ebe2010-03-15 10:12:16 +00004748static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4749 CXXScopeSpec &SS = D.getCXXScopeSpec();
4750 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004751 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004752}
4753
John McCall31168b02011-06-15 23:02:42 +00004754bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4755 QualType type = decl->getType();
4756 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4757 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4758 // Various kinds of declaration aren't allowed to be __autoreleasing.
4759 unsigned kind = -1U;
4760 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4761 if (var->hasAttr<BlocksAttr>())
4762 kind = 0; // __block
4763 else if (!var->hasLocalStorage())
4764 kind = 1; // global
4765 } else if (isa<ObjCIvarDecl>(decl)) {
4766 kind = 3; // ivar
4767 } else if (isa<FieldDecl>(decl)) {
4768 kind = 2; // field
4769 }
4770
4771 if (kind != -1U) {
4772 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4773 << kind;
4774 }
4775 } else if (lifetime == Qualifiers::OCL_None) {
4776 // Try to infer lifetime.
4777 if (!type->isObjCLifetimeType())
4778 return false;
4779
4780 lifetime = type->getObjCARCImplicitLifetime();
4781 type = Context.getLifetimeQualifiedType(type, lifetime);
4782 decl->setType(type);
4783 }
4784
4785 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4786 // Thread-local variables cannot have lifetime.
4787 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004788 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004789 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004790 << var->getType();
4791 return true;
4792 }
4793 }
4794
4795 return false;
4796}
4797
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004798static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4799 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004800 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004801 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004802 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4803 ND.dropAttr<WeakAttr>();
4804 }
4805 }
4806 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004807 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004808 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4809 ND.dropAttr<WeakRefAttr>();
4810 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004811 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004812
4813 // 'selectany' only applies to externally visible varable declarations.
4814 // It does not apply to functions.
4815 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4816 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4817 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4818 ND.dropAttr<SelectAnyAttr>();
4819 }
4820 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004821}
4822
John McCallc87d9722013-04-02 02:48:58 +00004823/// Given that we are within the definition of the given function,
4824/// will that definition behave like C99's 'inline', where the
4825/// definition is discarded except for optimization purposes?
4826static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4827 // Try to avoid calling GetGVALinkageForFunction.
4828
4829 // All cases of this require the 'inline' keyword.
4830 if (!FD->isInlined()) return false;
4831
4832 // This is only possible in C++ with the gnu_inline attribute.
4833 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4834 return false;
4835
4836 // Okay, go ahead and call the relatively-more-expensive function.
4837
4838#ifndef NDEBUG
4839 // AST quite reasonably asserts that it's working on a function
4840 // definition. We don't really have a way to tell it that we're
4841 // currently defining the function, so just lie to it in +Asserts
4842 // builds. This is an awful hack.
4843 FD->setLazyBody(1);
4844#endif
4845
4846 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4847
4848#ifndef NDEBUG
4849 FD->setLazyBody(0);
4850#endif
4851
4852 return isC99Inline;
4853}
4854
Richard Smithac974a32013-06-30 09:48:50 +00004855/// Determine whether a variable is extern "C" prior to attaching
4856/// an initializer. We can't just call isExternC() here, because that
4857/// will also compute and cache whether the declaration is externally
4858/// visible, which might change when we attach the initializer.
4859///
4860/// This can only be used if the declaration is known to not be a
4861/// redeclaration of an internal linkage declaration.
4862///
4863/// For instance:
4864///
4865/// auto x = []{};
4866///
4867/// Attaching the initializer here makes this declaration not externally
4868/// visible, because its type has internal linkage.
4869///
4870/// FIXME: This is a hack.
4871template<typename T>
4872static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4873 if (S.getLangOpts().CPlusPlus) {
4874 // In C++, the overloadable attribute negates the effects of extern "C".
4875 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4876 return false;
4877 }
4878 return D->isExternC();
4879}
4880
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004881static bool shouldConsiderLinkage(const VarDecl *VD) {
4882 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4883 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004884 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004885 if (DC->isFileContext())
4886 return true;
4887 if (DC->isRecord())
4888 return false;
4889 llvm_unreachable("Unexpected context");
4890}
4891
4892static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4893 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4894 if (DC->isFileContext() || DC->isFunctionOrMethod())
4895 return true;
4896 if (DC->isRecord())
4897 return false;
4898 llvm_unreachable("Unexpected context");
4899}
4900
Richard Smith541b38b2013-09-20 01:15:31 +00004901/// Adjust the \c DeclContext for a function or variable that might be a
4902/// function-local external declaration.
4903bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4904 if (!DC->isFunctionOrMethod())
4905 return false;
4906
4907 // If this is a local extern function or variable declared within a function
4908 // template, don't add it into the enclosing namespace scope until it is
4909 // instantiated; it might have a dependent type right now.
4910 if (DC->isDependentContext())
4911 return true;
4912
4913 // C++11 [basic.link]p7:
4914 // When a block scope declaration of an entity with linkage is not found to
4915 // refer to some other declaration, then that entity is a member of the
4916 // innermost enclosing namespace.
4917 //
4918 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4919 // semantically-enclosing namespace, not a lexically-enclosing one.
4920 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4921 DC = DC->getParent();
4922 return true;
4923}
4924
Larisse Voufo39a1e502013-08-06 01:03:05 +00004925NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00004926Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004927 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004928 MultiTemplateParamsArg TemplateParamLists,
4929 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004930 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004931 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004932
Douglas Gregorc4df4072010-04-19 22:54:31 +00004933 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00004934 VarDecl::StorageClass SC =
4935 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00004936
Richard Smith541b38b2013-09-20 01:15:31 +00004937 DeclContext *OriginalDC = DC;
4938 bool IsLocalExternDecl = SC == SC_Extern &&
4939 adjustContextForLocalExternDecl(DC);
4940
Richard Smith5990db62013-04-15 08:33:22 +00004941 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004942 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4943 // half array type (unless the cl_khr_fp16 extension is enabled).
4944 if (Context.getBaseElementType(R)->isHalfType()) {
4945 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4946 D.setInvalidType();
4947 }
4948 }
4949
Douglas Gregorc4df4072010-04-19 22:54:31 +00004950 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004951 // mutable can only appear on non-static class members, so it's always
4952 // an error here
4953 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004954 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004955 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004956 }
John McCallc87d9722013-04-02 02:48:58 +00004957
Richard Smithf2c9afc2013-06-17 01:34:01 +00004958 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4959 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4960 D.getDeclSpec().getStorageClassSpecLoc())) {
4961 // In C++11, the 'register' storage class specifier is deprecated.
4962 // Suppress the warning in system macros, it's used in macros in some
4963 // popular C system headers, such as in glibc's htonl() macro.
4964 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4965 diag::warn_deprecated_register)
4966 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4967 }
4968
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004969 IdentifierInfo *II = Name.getAsIdentifierInfo();
4970 if (!II) {
4971 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00004972 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004973 return 0;
4974 }
4975
Richard Smithb1402ae2013-03-18 22:52:47 +00004976 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00004977
Douglas Gregor212cab32009-03-11 20:22:50 +00004978 if (!DC->isRecord() && S->getFnParent() == 0) {
4979 // C99 6.9p2: The storage-class specifiers auto and register shall not
4980 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00004981 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00004982 // If this is a register variable with an asm label specified, then this
4983 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00004984 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00004985 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4986 else
4987 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004988 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004989 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004990 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00004991
David Blaikiebbafb8a2012-03-11 07:00:24 +00004992 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00004993 // Set up the special work-group-local storage class for variables in the
4994 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00004995 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00004996 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00004997 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004998
Guy Benyei61054192013-02-07 10:55:47 +00004999 // OpenCL v1.2 s6.9.b p4:
5000 // The sampler type cannot be used with the __local and __global address
5001 // space qualifiers.
5002 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5003 R.getAddressSpace() == LangAS::opencl_global)) {
5004 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5005 }
5006
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005007 // OpenCL 1.2 spec, p6.9 r:
5008 // The event type cannot be used to declare a program scope variable.
5009 // The event type cannot be used with the __local, __constant and __global
5010 // address space qualifiers.
5011 if (R->isEventT()) {
5012 if (S->getParent() == 0) {
5013 Diag(D.getLocStart(), diag::err_event_t_global_var);
5014 D.setInvalidType();
5015 }
5016
5017 if (R.getAddressSpace()) {
5018 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5019 D.setInvalidType();
5020 }
5021 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005022 }
5023
Larisse Voufo39a1e502013-08-06 01:03:05 +00005024 bool IsExplicitSpecialization = false;
5025 bool IsVariableTemplateSpecialization = false;
5026 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005027 bool IsVariableTemplate = false;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005028 VarTemplateDecl *PrevVarTemplate = 0;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005029 VarDecl *NewVD = 0;
5030 VarTemplateDecl *NewTemplate = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005031 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005032 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005033 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005034 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005035
5036 if (D.isInvalidType())
5037 NewVD->setInvalidDecl();
5038 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005039 bool Invalid = false;
5040
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005041 if (DC->isRecord() && !CurContext->isRecord()) {
5042 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005043 switch (SC) {
5044 case SC_None:
5045 break;
5046 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005047 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5048 diag::err_static_out_of_line)
5049 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005050 break;
5051 case SC_Auto:
5052 case SC_Register:
5053 case SC_Extern:
5054 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5055 // to names of variables declared in a block or to function parameters.
5056 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5057 // of class members
5058
5059 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5060 diag::err_storage_class_for_static_member)
5061 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5062 break;
5063 case SC_PrivateExtern:
5064 llvm_unreachable("C storage class in c++!");
5065 case SC_OpenCLWorkGroupLocal:
5066 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005067 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005068 }
5069
Richard Smith42973752012-02-16 20:41:22 +00005070 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005071 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5072 if (RD->isLocalClass())
5073 Diag(D.getIdentifierLoc(),
5074 diag::err_static_data_member_not_allowed_in_local_class)
5075 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005076
Richard Smith42973752012-02-16 20:41:22 +00005077 // C++98 [class.union]p1: If a union contains a static data member,
5078 // the program is ill-formed. C++11 drops this restriction.
5079 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005080 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005081 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005082 ? diag::warn_cxx98_compat_static_data_member_in_union
5083 : diag::ext_static_data_member_in_union) << Name;
5084 // We conservatively disallow static data members in anonymous structs.
5085 else if (!RD->getDeclName())
5086 Diag(D.getIdentifierLoc(),
5087 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005088 << Name << RD->isUnion();
5089 }
5090 }
5091
Larisse Voufo39a1e502013-08-06 01:03:05 +00005092 NamedDecl *PrevDecl = 0;
5093 if (Previous.begin() != Previous.end())
5094 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5095 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5096
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005097 // Match up the template parameter lists with the scope specifier, then
5098 // determine whether we have a template or a template specialization.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005099 TemplateParameterList *TemplateParams =
5100 MatchTemplateParametersToScopeSpecifier(
5101 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5102 D.getCXXScopeSpec(), TemplateParamLists,
5103 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005104 if (TemplateParams) {
5105 if (!TemplateParams->size() &&
5106 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005107 // There is an extraneous 'template<>' for this variable. Complain
5108 // about it, but allow the declaration of the variable.
5109 Diag(TemplateParams->getTemplateLoc(),
5110 diag::err_template_variable_noparams)
5111 << II
5112 << SourceRange(TemplateParams->getTemplateLoc(),
5113 TemplateParams->getRAngleLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005114 } else {
5115 // Only C++1y supports variable templates (N3651).
5116 Diag(D.getIdentifierLoc(),
5117 getLangOpts().CPlusPlus1y
5118 ? diag::warn_cxx11_compat_variable_template
5119 : diag::ext_variable_template);
5120
5121 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5122 // This is an explicit specialization or a partial specialization.
5123 // Check that we can declare a specialization here
5124
5125 IsVariableTemplateSpecialization = true;
5126 IsPartialSpecialization = TemplateParams->size() > 0;
5127
5128 } else { // if (TemplateParams->size() > 0)
Larisse Voufo21de36b2013-08-06 03:43:07 +00005129 // This is a template declaration.
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005130 IsVariableTemplate = true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005131
5132 // Check that we can declare a template here.
5133 if (CheckTemplateDeclScope(S, TemplateParams))
5134 return 0;
5135
5136 // If there is a previous declaration with the same name, check
5137 // whether this is a valid redeclaration.
5138 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5139 PrevDecl = PrevVarTemplate = 0;
5140
5141 if (PrevVarTemplate) {
5142 // Ensure that the template parameter lists are compatible.
5143 if (!TemplateParameterListsAreEqual(
5144 TemplateParams, PrevVarTemplate->getTemplateParameters(),
5145 /*Complain=*/true, TPL_TemplateMatch))
5146 return 0;
5147 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5148 // Maybe we will complain about the shadowed template parameter.
5149 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5150
5151 // Just pretend that we didn't see the previous declaration.
5152 PrevDecl = 0;
5153 } else if (PrevDecl) {
5154 // C++ [temp]p5:
5155 // ... a template name declared in namespace scope or in class
5156 // scope shall be unique in that scope.
5157 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5158 << Name;
5159 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5160 return 0;
5161 }
5162
5163 // Check the template parameter list of this declaration, possibly
5164 // merging in the template parameter list from the previous variable
5165 // template declaration.
5166 if (CheckTemplateParameterList(
5167 TemplateParams,
5168 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5169 : 0,
5170 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5171 DC->isDependentContext())
5172 ? TPC_ClassTemplateMember
5173 : TPC_VarTemplate))
5174 Invalid = true;
5175
5176 if (D.getCXXScopeSpec().isSet()) {
5177 // If the name of the template was qualified, we must be defining
5178 // the template out-of-line.
5179 if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5180 !PrevVarTemplate) {
Richard Smith114394f2013-08-09 04:35:01 +00005181 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5182 << Name << DC << /*IsDefinition*/true
5183 << D.getCXXScopeSpec().getRange();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005184 Invalid = true;
5185 }
5186 }
5187 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005188 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005189 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5190 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5191
5192 // We have encountered something that the user meant to be a
5193 // specialization (because it has explicitly-specified template
5194 // arguments) but that was not introduced with a "template<>" (or had
5195 // too few of them).
5196 // FIXME: Differentiate between attempts for explicit instantiations
5197 // (starting with "template") and the rest.
5198 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5199 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5200 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5201 "template<> ");
5202 IsVariableTemplateSpecialization = true;
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005203 }
Mike Stump11289f42009-09-09 15:08:12 +00005204
Larisse Voufo39a1e502013-08-06 01:03:05 +00005205 if (IsVariableTemplateSpecialization) {
5206 if (!PrevVarTemplate) {
5207 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5208 << IsPartialSpecialization;
5209 return 0;
5210 }
5211
5212 SourceLocation TemplateKWLoc =
5213 TemplateParamLists.size() > 0
5214 ? TemplateParamLists[0]->getTemplateLoc()
5215 : SourceLocation();
5216 DeclResult Res = ActOnVarTemplateSpecialization(
5217 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5218 IsPartialSpecialization);
5219 if (Res.isInvalid())
5220 return 0;
5221 NewVD = cast<VarDecl>(Res.get());
5222 AddToScope = false;
5223 } else
5224 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5225 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005226
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005227 // If this is supposed to be a variable template, create it as such.
5228 if (IsVariableTemplate) {
5229 NewTemplate =
5230 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5231 TemplateParams, NewVD, PrevVarTemplate);
5232 NewVD->setDescribedVarTemplate(NewTemplate);
5233 }
5234
Richard Smithb2bc2e62011-02-21 20:05:19 +00005235 // If this decl has an auto type in need of deduction, make a note of the
5236 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005237 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005238 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005239
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005240 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005241 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005242 if (NewTemplate)
5243 NewTemplate->setInvalidDecl();
5244 }
Mike Stump11289f42009-09-09 15:08:12 +00005245
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005246 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005247
Larisse Voufo39a1e502013-08-06 01:03:05 +00005248 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5249 if (TemplateParams && TemplateParamLists.size() > 1 &&
5250 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5251 NewVD->setTemplateParameterListsInfo(
5252 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5253 } else if (IsVariableTemplateSpecialization ||
5254 (!TemplateParams && TemplateParamLists.size() > 0 &&
5255 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005256 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00005257 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005258 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005259 }
Richard Smitha77a0a62011-08-15 21:04:07 +00005260
Richard Smith6331c402012-02-13 22:16:19 +00005261 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005262 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005263 }
5264
Douglas Gregor41866812011-09-12 18:37:38 +00005265 // Set the lexical context. If the declarator has a C++ scope specifier, the
5266 // lexical context will be different from the semantic context.
5267 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005268 if (NewTemplate)
5269 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005270
Richard Smith541b38b2013-09-20 01:15:31 +00005271 if (IsLocalExternDecl)
5272 NewVD->setLocalExternDecl();
5273
Richard Smithb4a9e862013-04-12 22:46:28 +00005274 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005275 if (NewVD->hasLocalStorage()) {
5276 // C++11 [dcl.stc]p4:
5277 // When thread_local is applied to a variable of block scope the
5278 // storage-class-specifier static is implied if it does not appear
5279 // explicitly.
5280 // Core issue: 'static' is not implied if the variable is declared
5281 // 'extern'.
5282 if (SCSpec == DeclSpec::SCS_unspecified &&
5283 TSCS == DeclSpec::TSCS_thread_local &&
5284 DC->isFunctionOrMethod())
5285 NewVD->setTSCSpec(TSCS);
5286 else
5287 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5288 diag::err_thread_non_global)
5289 << DeclSpec::getSpecifierName(TSCS);
5290 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005291 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5292 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005293 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005294 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005295 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005296
John McCallc87d9722013-04-02 02:48:58 +00005297 // C99 6.7.4p3
5298 // An inline definition of a function with external linkage shall
5299 // not contain a definition of a modifiable object with static or
5300 // thread storage duration...
5301 // We only apply this when the function is required to be defined
5302 // elsewhere, i.e. when the function is not 'extern inline'. Note
5303 // that a local variable with thread storage duration still has to
5304 // be marked 'static'. Also note that it's possible to get these
5305 // semantics in C++ using __attribute__((gnu_inline)).
5306 if (SC == SC_Static && S->getFnParent() != 0 &&
5307 !NewVD->getType().isConstQualified()) {
5308 FunctionDecl *CurFD = getCurFunctionDecl();
5309 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5310 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5311 diag::warn_static_local_in_extern_inline);
5312 MaybeSuggestAddingStaticToDecl(CurFD);
5313 }
5314 }
5315
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005316 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005317 if (IsVariableTemplateSpecialization)
5318 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5319 << (IsPartialSpecialization ? 1 : 0)
5320 << FixItHint::CreateRemoval(
5321 D.getDeclSpec().getModulePrivateSpecLoc());
5322 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005323 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5324 << 2
5325 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005326 else if (NewVD->hasLocalStorage())
5327 Diag(NewVD->getLocation(), diag::err_module_private_local)
5328 << 0 << NewVD->getDeclName()
5329 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5330 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005331 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005332 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005333 if (NewTemplate)
5334 NewTemplate->setModulePrivate();
5335 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005336 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005337
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005338 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005339 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005340
Richard Smith848e1f12013-02-01 08:12:08 +00005341 if (NewVD->hasAttrs())
5342 CheckAlignasUnderalignment(NewVD);
5343
Peter Collingbournec6b08572012-08-28 20:37:50 +00005344 if (getLangOpts().CUDA) {
5345 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5346 // storage [duration]."
5347 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005348 (NewVD->hasAttr<CUDASharedAttr>() ||
5349 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005350 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005351 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005352 }
5353
John McCall31168b02011-06-15 23:02:42 +00005354 // In auto-retain/release, infer strong retension for variables of
5355 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005356 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005357 NewVD->setInvalidDecl();
5358
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005359 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005360 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005361 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005362 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005363 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005364 if (S->getFnParent() != 0) {
5365 switch (SC) {
5366 case SC_None:
5367 case SC_Auto:
5368 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5369 break;
5370 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005371 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005372 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5373 break;
5374 case SC_Static:
5375 case SC_Extern:
5376 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005377 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005378 break;
5379 }
5380 }
5381
5382 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00005383 Context, Label));
David Chisnall0867d9c2012-02-18 16:12:34 +00005384 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5385 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5386 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5387 if (I != ExtnameUndeclaredIdentifiers.end()) {
5388 NewVD->addAttr(I->second);
5389 ExtnameUndeclaredIdentifiers.erase(I);
5390 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005391 }
5392
John McCalla2a3f7d2010-03-16 21:48:18 +00005393 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00005394 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00005395 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005396
John McCall1f82f242009-11-18 22:49:29 +00005397 // Don't consider existing declarations that are in a different
5398 // scope and are out-of-semantic-context declarations (if the new
5399 // declaration has linkage).
Larisse Voufo39a1e502013-08-06 01:03:05 +00005400 FilterLookupForScope(
Richard Smith541b38b2013-09-20 01:15:31 +00005401 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
Larisse Voufo39a1e502013-08-06 01:03:05 +00005402 IsExplicitSpecialization || IsVariableTemplateSpecialization);
5403
Richard Smith1c34fb72013-08-13 18:18:50 +00005404 // Check whether the previous declaration is in the same block scope. This
5405 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5406 if (getLangOpts().CPlusPlus &&
5407 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5408 NewVD->setPreviousDeclInSameBlockScope(
5409 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005410 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005411
David Blaikiebbafb8a2012-03-11 07:00:24 +00005412 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005413 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5414 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005415 // Merge the decl with the existing one if appropriate.
5416 if (!Previous.empty()) {
5417 if (Previous.isSingleResult() &&
5418 isa<FieldDecl>(Previous.getFoundDecl()) &&
5419 D.getCXXScopeSpec().isSet()) {
5420 // The user tried to define a non-static data member
5421 // out-of-line (C++ [dcl.meaning]p1).
5422 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5423 << D.getCXXScopeSpec().getRange();
5424 Previous.clear();
5425 NewVD->setInvalidDecl();
5426 }
5427 } else if (D.getCXXScopeSpec().isSet()) {
5428 // No previous declaration in the qualifying scope.
5429 Diag(D.getIdentifierLoc(), diag::err_no_member)
5430 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005431 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005432 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005433 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005434
Larisse Voufo39a1e502013-08-06 01:03:05 +00005435 if (!IsVariableTemplateSpecialization) {
5436 if (PrevVarTemplate) {
5437 LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5438 LookupOrdinaryName, ForRedeclaration);
5439 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005440 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
Larisse Voufo39a1e502013-08-06 01:03:05 +00005441 } else
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005442 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Larisse Voufo39a1e502013-08-06 01:03:05 +00005443 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005444
5445 // This is an explicit specialization of a static data member. Check it.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005446 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005447 CheckMemberSpecialization(NewVD, Previous))
5448 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005449 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005450
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005451 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005452 checkAttributesAfterMerging(*this, *NewVD);
5453
Richard Smithac974a32013-06-30 09:48:50 +00005454 // If this is the first declaration of an extern C variable, update
5455 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005456 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005457 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005458 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005459
Reid Klecknerd8110b62013-09-10 20:14:30 +00005460 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005461 Decl *ManglingContextDecl;
5462 if (MangleNumberingContext *MCtx =
5463 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5464 ManglingContextDecl)) {
5465 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5466 }
5467 }
5468
Larisse Voufo39a1e502013-08-06 01:03:05 +00005469 // If we are providing an explicit specialization of a static variable
5470 // template, make a note of that.
5471 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
Larisse Voufo4cda4612013-08-22 00:28:27 +00005472 PrevVarTemplate->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005473
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005474 if (NewTemplate) {
5475 ActOnDocumentableDecl(NewTemplate);
5476 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005477 }
5478
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005479 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005480}
5481
John McCalldf8b37c2010-03-22 09:20:08 +00005482/// \brief Diagnose variable or built-in function shadowing. Implements
5483/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005484///
John McCalldf8b37c2010-03-22 09:20:08 +00005485/// This method is called whenever a VarDecl is added to a "useful"
5486/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005487///
John McCall2d8c7602010-03-20 04:12:52 +00005488/// \param S the scope in which the shadowing name is being declared
5489/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005490///
John McCalldf8b37c2010-03-22 09:20:08 +00005491void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005492 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005493 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005494 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005495 return;
5496
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005497 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005498 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005499 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005500
5501 DeclContext *NewDC = D->getDeclContext();
5502
John McCall2d8c7602010-03-20 04:12:52 +00005503 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005504 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005505 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005506
John McCalla2a3f7d2010-03-16 21:48:18 +00005507 NamedDecl* ShadowedDecl = R.getFoundDecl();
5508 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5509 return;
5510
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005511 // Fields are not shadowed by variables in C++ static methods.
5512 if (isa<FieldDecl>(ShadowedDecl))
5513 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5514 if (MD->isStatic())
5515 return;
5516
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005517 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5518 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005519 // For shadowing external vars, make sure that we point to the global
5520 // declaration, not a locally scoped extern declaration.
5521 for (VarDecl::redecl_iterator
5522 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5523 I != E; ++I)
5524 if (I->isFileVarDecl()) {
5525 ShadowedDecl = *I;
5526 break;
5527 }
5528 }
5529
5530 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5531
John McCall2d8c7602010-03-20 04:12:52 +00005532 // Only warn about certain kinds of shadowing for class members.
5533 if (NewDC && NewDC->isRecord()) {
5534 // In particular, don't warn about shadowing non-class members.
5535 if (!OldDC->isRecord())
5536 return;
5537
5538 // TODO: should we warn about static data members shadowing
5539 // static data members from base classes?
5540
5541 // TODO: don't diagnose for inaccessible shadowed members.
5542 // This is hard to do perfectly because we might friend the
5543 // shadowing context, but that's just a false negative.
5544 }
5545
5546 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005547 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005548 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005549 if (isa<FieldDecl>(ShadowedDecl))
5550 Kind = 3; // field
5551 else
5552 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005553 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005554 Kind = 1; // global
5555 else
5556 Kind = 0; // local
5557
John McCall2d8c7602010-03-20 04:12:52 +00005558 DeclarationName Name = R.getLookupName();
5559
John McCalla2a3f7d2010-03-16 21:48:18 +00005560 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00005561 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005562 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5563}
5564
John McCalldf8b37c2010-03-22 09:20:08 +00005565/// \brief Check -Wshadow without the advantage of a previous lookup.
5566void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005567 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005568 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005569 return;
5570
John McCalldf8b37c2010-03-22 09:20:08 +00005571 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5572 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5573 LookupName(R, S);
5574 CheckShadow(S, D, R);
5575}
5576
Richard Smithac974a32013-06-30 09:48:50 +00005577/// Check for conflict between this global or extern "C" declaration and
5578/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005579template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005580static bool checkGlobalOrExternCConflict(
5581 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5582 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5583 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005584
Richard Smithac974a32013-06-30 09:48:50 +00005585 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5586 // The common case: this global doesn't conflict with any extern "C"
5587 // declaration.
5588 return false;
5589 }
5590
5591 if (Prev) {
5592 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5593 // Both the old and new declarations have C language linkage. This is a
5594 // redeclaration.
5595 Previous.clear();
5596 Previous.addDecl(Prev);
5597 return true;
5598 }
5599
5600 // This is a global, non-extern "C" declaration, and there is a previous
5601 // non-global extern "C" declaration. Diagnose if this is a variable
5602 // declaration.
5603 if (!isa<VarDecl>(ND))
5604 return false;
5605 } else {
5606 // The declaration is extern "C". Check for any declaration in the
5607 // translation unit which might conflict.
5608 if (IsGlobal) {
5609 // We have already performed the lookup into the translation unit.
5610 IsGlobal = false;
5611 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5612 I != E; ++I) {
5613 if (isa<VarDecl>(*I)) {
5614 Prev = *I;
5615 break;
5616 }
5617 }
5618 } else {
5619 DeclContext::lookup_result R =
5620 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5621 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5622 I != E; ++I) {
5623 if (isa<VarDecl>(*I)) {
5624 Prev = *I;
5625 break;
5626 }
5627 // FIXME: If we have any other entity with this name in global scope,
5628 // the declaration is ill-formed, but that is a defect: it breaks the
5629 // 'stat' hack, for instance. Only variables can have mangled name
5630 // clashes with extern "C" declarations, so only they deserve a
5631 // diagnostic.
5632 }
5633 }
5634
5635 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005636 return false;
5637 }
5638
Richard Smithac974a32013-06-30 09:48:50 +00005639 // Use the first declaration's location to ensure we point at something which
5640 // is lexically inside an extern "C" linkage-spec.
5641 assert(Prev && "should have found a previous declaration to diagnose");
5642 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005643 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005644 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005645 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005646
5647 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5648 << IsGlobal << ND;
5649 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5650 << IsGlobal;
5651 return false;
5652}
5653
5654/// Apply special rules for handling extern "C" declarations. Returns \c true
5655/// if we have found that this is a redeclaration of some prior entity.
5656///
5657/// Per C++ [dcl.link]p6:
5658/// Two declarations [for a function or variable] with C language linkage
5659/// with the same name that appear in different scopes refer to the same
5660/// [entity]. An entity with C language linkage shall not be declared with
5661/// the same name as an entity in global scope.
5662template<typename T>
5663static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5664 LookupResult &Previous) {
5665 if (!S.getLangOpts().CPlusPlus) {
5666 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005667 // variable declared in function scope. We don't need this in C++, because
5668 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005669 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5670 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5671 Previous.clear();
5672 Previous.addDecl(Prev);
5673 return true;
5674 }
5675 }
5676 return false;
5677 }
5678
5679 // A declaration in the translation unit can conflict with an extern "C"
5680 // declaration.
5681 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5682 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5683
5684 // An extern "C" declaration can conflict with a declaration in the
5685 // translation unit or can be a redeclaration of an extern "C" declaration
5686 // in another scope.
5687 if (isIncompleteDeclExternC(S,ND))
5688 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5689
5690 // Neither global nor extern "C": nothing to do.
5691 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005692}
5693
Richard Smith27d807c2013-04-30 13:56:41 +00005694void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005695 // If the decl is already known invalid, don't check it.
5696 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005697 return;
Mike Stump11289f42009-09-09 15:08:12 +00005698
Abramo Bagnara341ab732012-11-08 14:44:42 +00005699 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5700 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005701
Richard Smith27d807c2013-04-30 13:56:41 +00005702 // Defer checking an 'auto' type until its initializer is attached.
5703 if (T->isUndeducedType())
5704 return;
5705
John McCall8b07ec22010-05-15 11:32:37 +00005706 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005707 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5708 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005709 T = Context.getObjCObjectPointerType(T);
5710 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005711 }
Mike Stump11289f42009-09-09 15:08:12 +00005712
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005713 // Emit an error if an address space was applied to decl with local storage.
5714 // This includes arrays of objects with address space qualifiers, but not
5715 // automatic variables that point to other address spaces.
5716 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005717 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005718 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005719 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005720 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005721 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005722
Tanya Lattner713eef42013-04-05 20:14:50 +00005723 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5724 // __constant address space.
5725 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5726 && T.getAddressSpace() != LangAS::opencl_constant
5727 && !T->isSamplerT()){
5728 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5729 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005730 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005731 }
5732
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005733 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5734 // scope.
5735 if ((getLangOpts().OpenCLVersion >= 120)
5736 && NewVD->isStaticLocal()) {
5737 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5738 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005739 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005740 }
5741
Mike Stumpca5ae662009-04-14 00:57:29 +00005742 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005743 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005744 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005745 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005746 else {
5747 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005748 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005749 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005750 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005751
Chris Lattner9fecd742009-04-19 05:21:20 +00005752 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005753 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005754 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005755 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005756
Chris Lattner9fecd742009-04-19 05:21:20 +00005757 if ((isVM && NewVD->hasLinkage()) ||
5758 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005759 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005760 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005761 TypeSourceInfo *FixedTInfo =
5762 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5763 SizeIsNegative, Oversized);
5764 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005765 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005766 // FIXME: This won't give the correct result for
5767 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005768 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005769
Anders Carlsson6c885802009-02-28 21:56:50 +00005770 if (NewVD->isFileVarDecl())
5771 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005772 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005773 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005774 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005775 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005776 else
5777 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005778 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005779 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005780 return;
Mike Stump11289f42009-09-09 15:08:12 +00005781 }
5782
Abramo Bagnara341ab732012-11-08 14:44:42 +00005783 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005784 if (NewVD->isFileVarDecl())
5785 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5786 else
5787 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005788 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005789 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005790 }
Mike Stump11289f42009-09-09 15:08:12 +00005791
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005792 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005793 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005794 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005795 }
5796
David Majnemer0ffa3312013-05-29 00:56:45 +00005797 if (T->isVoidType()) {
5798 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5799 // of objects and functions.
5800 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5801 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5802 << T;
5803 NewVD->setInvalidDecl();
5804 return;
5805 }
Richard Smith27d807c2013-04-30 13:56:41 +00005806 }
5807
5808 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5809 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5810 NewVD->setInvalidDecl();
5811 return;
5812 }
5813
5814 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5815 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5816 NewVD->setInvalidDecl();
5817 return;
5818 }
5819
5820 if (NewVD->isConstexpr() && !T->isDependentType() &&
5821 RequireLiteralType(NewVD->getLocation(), T,
5822 diag::err_constexpr_var_non_literal)) {
5823 // Can't perform this check until the type is deduced.
5824 NewVD->setInvalidDecl();
5825 return;
5826 }
5827}
5828
5829/// \brief Perform semantic checking on a newly-created variable
5830/// declaration.
5831///
5832/// This routine performs all of the type-checking required for a
5833/// variable declaration once it has been built. It is used both to
5834/// check variables after they have been parsed and their declarators
5835/// have been translated into a declaration, and to check variables
5836/// that have been instantiated from a template.
5837///
5838/// Sets NewVD->isInvalidDecl() if an error was encountered.
5839///
5840/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005841bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005842 CheckVariableDeclarationType(NewVD);
5843
5844 // If the decl is already known invalid, don't check it.
5845 if (NewVD->isInvalidDecl())
5846 return false;
5847
John McCallb65e8fe2013-04-01 18:34:28 +00005848 // If we did not find anything by this name, look for a non-visible
5849 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005850 if (Previous.empty() &&
5851 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005852 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005853
Douglas Gregor3552dab2013-01-09 00:47:56 +00005854 // Filter out any non-conflicting previous declarations.
5855 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5856
John McCall1f82f242009-11-18 22:49:29 +00005857 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005858 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005859 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005860 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005861 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005862}
5863
Douglas Gregor36d1b142009-10-06 17:59:45 +00005864/// \brief Data used with FindOverriddenMethod
5865struct FindOverriddenMethodData {
5866 Sema *S;
5867 CXXMethodDecl *Method;
5868};
5869
5870/// \brief Member lookup function that determines whether a given C++
5871/// method overrides a method in a base class, to be used with
5872/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005873static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005874 CXXBasePath &Path,
5875 void *UserData) {
5876 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005877
Douglas Gregor36d1b142009-10-06 17:59:45 +00005878 FindOverriddenMethodData *Data
5879 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005880
5881 DeclarationName Name = Data->Method->getDeclName();
5882
5883 // FIXME: Do we care about other names here too?
5884 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005885 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005886 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5887 CanQualType CT = Data->S->Context.getCanonicalType(T);
5888
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005889 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005890 }
5891
5892 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005893 !Path.Decls.empty();
5894 Path.Decls = Path.Decls.slice(1)) {
5895 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005896 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5897 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005898 return true;
5899 }
5900 }
5901
5902 return false;
5903}
5904
David Blaikie7e414262012-10-17 00:47:58 +00005905namespace {
5906 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5907}
5908/// \brief Report an error regarding overriding, along with any relevant
5909/// overriden methods.
5910///
5911/// \param DiagID the primary error to report.
5912/// \param MD the overriding method.
5913/// \param OEK which overrides to include as notes.
5914static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5915 OverrideErrorKind OEK = OEK_All) {
5916 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5917 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5918 E = MD->end_overridden_methods();
5919 I != E; ++I) {
5920 // This check (& the OEK parameter) could be replaced by a predicate, but
5921 // without lambdas that would be overkill. This is still nicer than writing
5922 // out the diag loop 3 times.
5923 if ((OEK == OEK_All) ||
5924 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5925 (OEK == OEK_Deleted && (*I)->isDeleted()))
5926 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5927 }
5928}
5929
Sebastian Redld5b24532009-11-18 21:51:29 +00005930/// AddOverriddenMethods - See if a method overrides any in the base classes,
5931/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005932bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00005933 // Look for virtual methods in base classes that this method might override.
5934 CXXBasePaths Paths;
5935 FindOverriddenMethodData Data;
5936 Data.Method = MD;
5937 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00005938 bool hasDeletedOverridenMethods = false;
5939 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005940 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00005941 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5942 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5943 E = Paths.found_decls_end(); I != E; ++I) {
5944 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00005945 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00005946 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00005947 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00005948 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00005949 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00005950 hasDeletedOverridenMethods |= OldMD->isDeleted();
5951 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005952 AddedAny = true;
5953 }
Sebastian Redld5b24532009-11-18 21:51:29 +00005954 }
5955 }
5956 }
David Blaikie7e414262012-10-17 00:47:58 +00005957
5958 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5959 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5960 }
5961 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5962 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5963 }
5964
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005965 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00005966}
5967
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005968namespace {
5969 // Struct for holding all of the extra arguments needed by
5970 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5971 struct ActOnFDArgs {
5972 Scope *S;
5973 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005974 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005975 bool AddToScope;
5976 };
5977}
5978
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005979namespace {
5980
5981// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005982// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005983class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5984 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005985 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5986 CXXRecordDecl *Parent)
5987 : Context(Context), OriginalFD(TypoFD),
5988 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005989
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005990 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005991 if (candidate.getEditDistance() == 0)
5992 return false;
5993
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005994 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005995 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5996 CDeclEnd = candidate.end();
5997 CDecl != CDeclEnd; ++CDecl) {
5998 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5999
6000 if (FD && !FD->hasBody() &&
6001 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6002 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6003 CXXRecordDecl *Parent = MD->getParent();
6004 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6005 return true;
6006 } else if (!ExpectedParent) {
6007 return true;
6008 }
6009 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006010 }
6011
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006012 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006013 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006014
6015 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006016 ASTContext &Context;
6017 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006018 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006019};
6020
6021}
6022
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006023/// \brief Generate diagnostics for an invalid function redeclaration.
6024///
6025/// This routine handles generating the diagnostic messages for an invalid
6026/// function redeclaration, including finding possible similar declarations
6027/// or performing typo correction if there are no previous declarations with
6028/// the same name.
6029///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006030/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006031/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006032static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006033 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006034 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006035 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006036 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006037 SmallVector<unsigned, 1> MismatchedParams;
6038 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006039 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006040 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006041 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6042 : diag::err_member_decl_does_not_match;
6043 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6044 IsLocalFriend ? Sema::LookupLocalFriendName
6045 : Sema::LookupOrdinaryName,
6046 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006047
6048 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006049 if (IsLocalFriend)
6050 SemaRef.LookupName(Prev, S);
6051 else
6052 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006053 assert(!Prev.isAmbiguous() &&
6054 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006055 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006056 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6057 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006058 if (!Prev.empty()) {
6059 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6060 Func != FuncEnd; ++Func) {
6061 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006062 if (FD &&
6063 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006064 // Add 1 to the index so that 0 can mean the mismatch didn't
6065 // involve a parameter
6066 unsigned ParamNum =
6067 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6068 NearMatches.push_back(std::make_pair(FD, ParamNum));
6069 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006070 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006071 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006072 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006073 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6074 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6075 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006076 // Set up everything for the call to ActOnFunctionDeclarator
6077 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6078 ExtraArgs.D.getIdentifierLoc());
6079 Previous.clear();
6080 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006081 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6082 CDeclEnd = Correction.end();
6083 CDecl != CDeclEnd; ++CDecl) {
6084 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006085 if (FD && !FD->hasBody() &&
6086 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006087 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006088 }
6089 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006090 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006091
6092 NamedDecl *Result;
6093 // Retry building the function declaration with the new previous
6094 // declarations, and with errors suppressed.
6095 {
6096 // Trap errors.
6097 Sema::SFINAETrap Trap(SemaRef);
6098
6099 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6100 // pieces need to verify the typo-corrected C++ declaration and hopefully
6101 // eliminate the need for the parameter pack ExtraArgs.
6102 Result = SemaRef.ActOnFunctionDeclarator(
6103 ExtraArgs.S, ExtraArgs.D,
6104 Correction.getCorrectionDecl()->getDeclContext(),
6105 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6106 ExtraArgs.AddToScope);
6107
6108 if (Trap.hasErrorOccurred())
6109 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006110 }
Richard Smithf9b15102013-08-17 00:46:16 +00006111
6112 if (Result) {
6113 // Determine which correction we picked.
6114 Decl *Canonical = Result->getCanonicalDecl();
6115 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6116 I != E; ++I)
6117 if ((*I)->getCanonicalDecl() == Canonical)
6118 Correction.setCorrectionDecl(*I);
6119
6120 SemaRef.diagnoseTypo(
6121 Correction,
6122 SemaRef.PDiag(IsLocalFriend
6123 ? diag::err_no_matching_local_friend_suggest
6124 : diag::err_member_decl_does_not_match_suggest)
6125 << Name << NewDC << IsDefinition);
6126 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006127 }
Richard Smithf9b15102013-08-17 00:46:16 +00006128
6129 // Pretend the typo correction never occurred
6130 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6131 ExtraArgs.D.getIdentifierLoc());
6132 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6133 Previous.clear();
6134 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006135 }
6136
Richard Smithf9b15102013-08-17 00:46:16 +00006137 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6138 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006139
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006140 bool NewFDisConst = false;
6141 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006142 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006143
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006144 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006145 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6146 NearMatch != NearMatchEnd; ++NearMatch) {
6147 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006148 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6149 bool FDisConst = MD && MD->isConst();
6150 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006151
Richard Smith541b38b2013-09-20 01:15:31 +00006152 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006153 if (unsigned Idx = NearMatch->second) {
6154 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006155 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6156 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006157 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6158 : diag::note_local_decl_close_param_match)
6159 << Idx << FDParam->getType()
6160 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006161 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006162 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006163 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006164 } else
Richard Smith114394f2013-08-09 04:35:01 +00006165 SemaRef.Diag(FD->getLocation(),
6166 IsMember ? diag::note_member_def_close_match
6167 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006168 }
Richard Smithf9b15102013-08-17 00:46:16 +00006169 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006170}
6171
David Blaikie30d15442011-10-19 22:56:21 +00006172static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6173 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006174 switch (D.getDeclSpec().getStorageClassSpec()) {
6175 default: llvm_unreachable("Unknown storage class!");
6176 case DeclSpec::SCS_auto:
6177 case DeclSpec::SCS_register:
6178 case DeclSpec::SCS_mutable:
6179 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6180 diag::err_typecheck_sclass_func);
6181 D.setInvalidType();
6182 break;
6183 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006184 case DeclSpec::SCS_extern:
6185 if (D.getDeclSpec().isExternInLinkageSpec())
6186 return SC_None;
6187 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006188 case DeclSpec::SCS_static: {
6189 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6190 // C99 6.7.1p5:
6191 // The declaration of an identifier for a function that has
6192 // block scope shall have no explicit storage-class specifier
6193 // other than extern
6194 // See also (C++ [dcl.stc]p4).
6195 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6196 diag::err_static_block_func);
6197 break;
6198 } else
6199 return SC_Static;
6200 }
6201 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6202 }
6203
6204 // No explicit storage class has already been returned
6205 return SC_None;
6206}
6207
6208static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6209 DeclContext *DC, QualType &R,
6210 TypeSourceInfo *TInfo,
6211 FunctionDecl::StorageClass SC,
6212 bool &IsVirtualOkay) {
6213 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6214 DeclarationName Name = NameInfo.getName();
6215
6216 FunctionDecl *NewFD = 0;
6217 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006218
David Blaikiebbafb8a2012-03-11 07:00:24 +00006219 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006220 // Determine whether the function was written with a
6221 // prototype. This true when:
6222 // - there is a prototype in the declarator, or
6223 // - the type R of the function is some kind of typedef or other reference
6224 // to a type name (which eventually refers to a function type).
6225 bool HasPrototype =
6226 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6227 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6228
David Blaikie30d15442011-10-19 22:56:21 +00006229 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006230 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006231 TInfo, SC, isInline,
6232 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006233 if (D.isInvalidType())
6234 NewFD->setInvalidDecl();
6235
6236 // Set the lexical context.
6237 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6238
6239 return NewFD;
6240 }
6241
6242 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6243 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6244
6245 // Check that the return type is not an abstract class type.
6246 // For record types, this is done by the AbstractClassUsageDiagnoser once
6247 // the class has been completely parsed.
6248 if (!DC->isRecord() &&
6249 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6250 R->getAs<FunctionType>()->getResultType(),
6251 diag::err_abstract_type_in_decl,
6252 SemaRef.AbstractReturnType))
6253 D.setInvalidType();
6254
6255 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6256 // This is a C++ constructor declaration.
6257 assert(DC->isRecord() &&
6258 "Constructors can only be declared in a member context");
6259
6260 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6261 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006262 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006263 R, TInfo, isExplicit, isInline,
6264 /*isImplicitlyDeclared=*/false,
6265 isConstexpr);
6266
6267 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6268 // This is a C++ destructor declaration.
6269 if (DC->isRecord()) {
6270 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6271 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6272 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6273 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006274 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006275 NameInfo, R, TInfo, isInline,
6276 /*isImplicitlyDeclared=*/false);
6277
6278 // If the class is complete, then we now create the implicit exception
6279 // specification. If the class is incomplete or dependent, we can't do
6280 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006281 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006282 Record->getDefinition() && !Record->isBeingDefined() &&
6283 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6284 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6285 }
6286
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006287 // The Microsoft ABI requires that we perform the destructor body
6288 // checks (i.e. operator delete() lookup) at every declaration, as
6289 // any translation unit may need to emit a deleting destructor.
6290 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6291 !Record->isDependentType() && Record->getDefinition() &&
6292 !Record->isBeingDefined()) {
6293 SemaRef.CheckDestructor(NewDD);
6294 }
6295
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006296 IsVirtualOkay = true;
6297 return NewDD;
6298
6299 } else {
6300 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6301 D.setInvalidType();
6302
6303 // Create a FunctionDecl to satisfy the function definition parsing
6304 // code path.
6305 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006306 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006307 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006308 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006309 /*hasPrototype=*/true, isConstexpr);
6310 }
6311
6312 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6313 if (!DC->isRecord()) {
6314 SemaRef.Diag(D.getIdentifierLoc(),
6315 diag::err_conv_function_not_member);
6316 return 0;
6317 }
6318
6319 SemaRef.CheckConversionDeclarator(D, R, SC);
6320 IsVirtualOkay = true;
6321 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006322 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006323 R, TInfo, isInline, isExplicit,
6324 isConstexpr, SourceLocation());
6325
6326 } else if (DC->isRecord()) {
6327 // If the name of the function is the same as the name of the record,
6328 // then this must be an invalid constructor that has a return type.
6329 // (The parser checks for a return type and makes the declarator a
6330 // constructor if it has no return type).
6331 if (Name.getAsIdentifierInfo() &&
6332 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6333 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6334 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6335 << SourceRange(D.getIdentifierLoc());
6336 return 0;
6337 }
6338
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006339 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006340 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6341 cast<CXXRecordDecl>(DC),
6342 D.getLocStart(), NameInfo, R,
6343 TInfo, SC, isInline,
6344 isConstexpr, SourceLocation());
6345 IsVirtualOkay = !Ret->isStatic();
6346 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006347 } else {
6348 // Determine whether the function was written with a
6349 // prototype. This true when:
6350 // - we're in C++ (where every function has a prototype),
6351 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006352 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006353 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006354 true/*HasPrototype*/, isConstexpr);
6355 }
6356}
6357
Eli Friedman8f5e9832012-09-20 01:40:23 +00006358void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6359 // In C++, the empty parameter-type-list must be spelled "void"; a
6360 // typedef of void is not permitted.
6361 if (getLangOpts().CPlusPlus &&
6362 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6363 bool IsTypeAlias = false;
6364 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6365 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6366 else if (const TemplateSpecializationType *TST =
6367 Param->getType()->getAs<TemplateSpecializationType>())
6368 IsTypeAlias = TST->isTypeAlias();
6369 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6370 << IsTypeAlias;
6371 }
6372}
6373
Matt Arsenaultefb38192013-07-23 01:23:36 +00006374enum OpenCLParamType {
6375 ValidKernelParam,
6376 PtrPtrKernelParam,
6377 PtrKernelParam,
6378 InvalidKernelParam,
6379 RecordKernelParam
6380};
6381
6382static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6383 if (PT->isPointerType()) {
6384 QualType PointeeType = PT->getPointeeType();
6385 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6386 }
6387
6388 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6389 // be used as builtin types.
6390
6391 if (PT->isImageType())
6392 return PtrKernelParam;
6393
6394 if (PT->isBooleanType())
6395 return InvalidKernelParam;
6396
6397 if (PT->isEventT())
6398 return InvalidKernelParam;
6399
6400 if (PT->isHalfType())
6401 return InvalidKernelParam;
6402
6403 if (PT->isRecordType())
6404 return RecordKernelParam;
6405
6406 return ValidKernelParam;
6407}
6408
6409static void checkIsValidOpenCLKernelParameter(
6410 Sema &S,
6411 Declarator &D,
6412 ParmVarDecl *Param,
6413 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6414 QualType PT = Param->getType();
6415
6416 // Cache the valid types we encounter to avoid rechecking structs that are
6417 // used again
6418 if (ValidTypes.count(PT.getTypePtr()))
6419 return;
6420
6421 switch (getOpenCLKernelParameterType(PT)) {
6422 case PtrPtrKernelParam:
6423 // OpenCL v1.2 s6.9.a:
6424 // A kernel function argument cannot be declared as a
6425 // pointer to a pointer type.
6426 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6427 D.setInvalidType();
6428 return;
6429
6430 // OpenCL v1.2 s6.9.k:
6431 // Arguments to kernel functions in a program cannot be declared with the
6432 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6433 // uintptr_t or a struct and/or union that contain fields declared to be
6434 // one of these built-in scalar types.
6435
6436 case InvalidKernelParam:
6437 // OpenCL v1.2 s6.8 n:
6438 // A kernel function argument cannot be declared
6439 // of event_t type.
6440 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6441 D.setInvalidType();
6442 return;
6443
6444 case PtrKernelParam:
6445 case ValidKernelParam:
6446 ValidTypes.insert(PT.getTypePtr());
6447 return;
6448
6449 case RecordKernelParam:
6450 break;
6451 }
6452
6453 // Track nested structs we will inspect
6454 SmallVector<const Decl *, 4> VisitStack;
6455
6456 // Track where we are in the nested structs. Items will migrate from
6457 // VisitStack to HistoryStack as we do the DFS for bad field.
6458 SmallVector<const FieldDecl *, 4> HistoryStack;
6459 HistoryStack.push_back((const FieldDecl *) 0);
6460
6461 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6462 VisitStack.push_back(PD);
6463
6464 assert(VisitStack.back() && "First decl null?");
6465
6466 do {
6467 const Decl *Next = VisitStack.pop_back_val();
6468 if (!Next) {
6469 assert(!HistoryStack.empty());
6470 // Found a marker, we have gone up a level
6471 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6472 ValidTypes.insert(Hist->getType().getTypePtr());
6473
6474 continue;
6475 }
6476
6477 // Adds everything except the original parameter declaration (which is not a
6478 // field itself) to the history stack.
6479 const RecordDecl *RD;
6480 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6481 HistoryStack.push_back(Field);
6482 RD = Field->getType()->castAs<RecordType>()->getDecl();
6483 } else {
6484 RD = cast<RecordDecl>(Next);
6485 }
6486
6487 // Add a null marker so we know when we've gone back up a level
6488 VisitStack.push_back((const Decl *) 0);
6489
6490 for (RecordDecl::field_iterator I = RD->field_begin(),
6491 E = RD->field_end(); I != E; ++I) {
6492 const FieldDecl *FD = *I;
6493 QualType QT = FD->getType();
6494
6495 if (ValidTypes.count(QT.getTypePtr()))
6496 continue;
6497
6498 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6499 if (ParamType == ValidKernelParam)
6500 continue;
6501
6502 if (ParamType == RecordKernelParam) {
6503 VisitStack.push_back(FD);
6504 continue;
6505 }
6506
6507 // OpenCL v1.2 s6.9.p:
6508 // Arguments to kernel functions that are declared to be a struct or union
6509 // do not allow OpenCL objects to be passed as elements of the struct or
6510 // union.
6511 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6512 S.Diag(Param->getLocation(),
6513 diag::err_record_with_pointers_kernel_param)
6514 << PT->isUnionType()
6515 << PT;
6516 } else {
6517 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6518 }
6519
6520 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6521 << PD->getDeclName();
6522
6523 // We have an error, now let's go back up through history and show where
6524 // the offending field came from
6525 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6526 E = HistoryStack.end(); I != E; ++I) {
6527 const FieldDecl *OuterField = *I;
6528 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6529 << OuterField->getType();
6530 }
6531
6532 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6533 << QT->isPointerType()
6534 << QT;
6535 D.setInvalidType();
6536 return;
6537 }
6538 } while (!VisitStack.empty());
6539}
6540
Mike Stump11289f42009-09-09 15:08:12 +00006541NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006542Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006543 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006544 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006545 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006546 QualType R = TInfo->getType();
6547
Zhongxing Xubece5d62009-01-16 01:13:29 +00006548 assert(R.getTypePtr()->isFunctionType());
6549
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006550 // TODO: consider using NameInfo for diagnostic.
6551 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6552 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006553 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006554
Richard Smithb4a9e862013-04-12 22:46:28 +00006555 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6556 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6557 diag::err_invalid_thread)
6558 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006559
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006560 if (D.isFirstDeclarationOfMember())
6561 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006562
Douglas Gregor513e63c2010-12-10 19:28:19 +00006563 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006564 FunctionTemplateDecl *FunctionTemplate = 0;
6565 bool isExplicitSpecialization = false;
6566 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006567
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006568 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006569 bool HasExplicitTemplateArgs = false;
6570 TemplateArgumentListInfo TemplateArgs;
6571
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006572 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006573
Richard Smith541b38b2013-09-20 01:15:31 +00006574 DeclContext *OriginalDC = DC;
6575 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6576
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006577 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6578 isVirtualOkay);
6579 if (!NewFD) return 0;
6580
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006581 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6582 NewFD->setTopLevelDeclInObjCContainer();
6583
Richard Smith541b38b2013-09-20 01:15:31 +00006584 // Set the lexical context. If this is a function-scope declaration, or has a
6585 // C++ scope specifier, or is the object of a friend declaration, the lexical
6586 // context will be different from the semantic context.
6587 NewFD->setLexicalDeclContext(CurContext);
6588
6589 if (IsLocalExternDecl)
6590 NewFD->setLocalExternDecl();
6591
David Blaikiebbafb8a2012-03-11 07:00:24 +00006592 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006593 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006594 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6595 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006596 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006597 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006598 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006599 // C++ [class.friend]p5
6600 // A function can be defined in a friend declaration of a
6601 // class . . . . Such a function is implicitly inline.
6602 NewFD->setImplicitlyInline();
6603 }
6604
John McCalldb632ac2012-09-25 07:32:39 +00006605 // If this is a method defined in an __interface, and is not a constructor
6606 // or an overloaded operator, then set the pure flag (isVirtual will already
6607 // return true).
6608 if (const CXXRecordDecl *Parent =
6609 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6610 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006611 NewFD->setPure(true);
6612 }
6613
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006614 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006615 isExplicitSpecialization = false;
6616 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006617 if (D.isInvalidType())
6618 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006619
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006620 // Match up the template parameter lists with the scope specifier, then
6621 // determine whether we have a template or a template specialization.
6622 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006623 if (TemplateParameterList *TemplateParams =
6624 MatchTemplateParametersToScopeSpecifier(
6625 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6626 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6627 isExplicitSpecialization, Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006628 if (TemplateParams->size() > 0) {
6629 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006630
Abramo Bagnara60804e12011-03-18 15:16:37 +00006631 // Check that we can declare a template here.
6632 if (CheckTemplateDeclScope(S, TemplateParams))
6633 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006634
Abramo Bagnara60804e12011-03-18 15:16:37 +00006635 // A destructor cannot be a template.
6636 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6637 Diag(NewFD->getLocation(), diag::err_destructor_template);
6638 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006639 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006640
6641 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006642 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006643 // now that we know what the current instantiation is.
6644 if (DC->isDependentContext()) {
6645 ContextRAII SavedContext(*this, DC);
6646 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6647 Invalid = true;
6648 }
6649
John McCall1f0479e2010-03-24 08:27:58 +00006650
Abramo Bagnara60804e12011-03-18 15:16:37 +00006651 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6652 NewFD->getLocation(),
6653 Name, TemplateParams,
6654 NewFD);
6655 FunctionTemplate->setLexicalDeclContext(CurContext);
6656 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6657
6658 // For source fidelity, store the other template param lists.
6659 if (TemplateParamLists.size() > 1) {
6660 NewFD->setTemplateParameterListsInfo(Context,
6661 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006662 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006663 }
6664 } else {
6665 // This is a function template specialization.
6666 isFunctionTemplateSpecialization = true;
6667 // For source fidelity, store all the template param lists.
6668 NewFD->setTemplateParameterListsInfo(Context,
6669 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006670 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006671
6672 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6673 if (isFriend) {
6674 // We want to remove the "template<>", found here.
6675 SourceRange RemoveRange = TemplateParams->getSourceRange();
6676
6677 // If we remove the template<> and the name is not a
6678 // template-id, we're actually silently creating a problem:
6679 // the friend declaration will refer to an untemplated decl,
6680 // and clearly the user wants a template specialization. So
6681 // we need to insert '<>' after the name.
6682 SourceLocation InsertLoc;
6683 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6684 InsertLoc = D.getName().getSourceRange().getEnd();
6685 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6686 }
6687
6688 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6689 << Name << RemoveRange
6690 << FixItHint::CreateRemoval(RemoveRange)
6691 << FixItHint::CreateInsertion(InsertLoc, "<>");
6692 }
6693 }
6694 }
6695 else {
6696 // All template param lists were matched against the scope specifier:
6697 // this is NOT (an explicit specialization of) a template.
6698 if (TemplateParamLists.size() > 0)
6699 // For source fidelity, store all the template param lists.
6700 NewFD->setTemplateParameterListsInfo(Context,
6701 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006702 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006703 }
6704
6705 if (Invalid) {
6706 NewFD->setInvalidDecl();
6707 if (FunctionTemplate)
6708 FunctionTemplate->setInvalidDecl();
6709 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006710
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006711 // C++ [dcl.fct.spec]p5:
6712 // The virtual specifier shall only be used in declarations of
6713 // nonstatic class member functions that appear within a
6714 // member-specification of a class declaration; see 10.3.
6715 //
6716 if (isVirtual && !NewFD->isInvalidDecl()) {
6717 if (!isVirtualOkay) {
6718 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6719 diag::err_virtual_non_function);
6720 } else if (!CurContext->isRecord()) {
6721 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006722 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6723 diag::err_virtual_out_of_class)
6724 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6725 } else if (NewFD->getDescribedFunctionTemplate()) {
6726 // C++ [temp.mem]p3:
6727 // A member function template shall not be virtual.
6728 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6729 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006730 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6731 } else {
6732 // Okay: Add virtual to the method.
6733 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006734 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006735
6736 if (getLangOpts().CPlusPlus1y &&
6737 NewFD->getResultType()->isUndeducedType())
6738 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006739 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006740
Richard Smithc1564702013-11-15 02:58:23 +00006741 if (getLangOpts().CPlusPlus1y &&
6742 (NewFD->isDependentContext() ||
6743 (isFriend && CurContext->isDependentContext())) &&
Richard Smithc58f38f2013-08-14 20:16:31 +00006744 NewFD->getResultType()->isUndeducedType()) {
6745 // If the function template is referenced directly (for instance, as a
6746 // member of the current instantiation), pretend it has a dependent type.
6747 // This is not really justified by the standard, but is the only sane
6748 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006749 // FIXME: For a friend function, we have not marked the function as being
6750 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006751 const FunctionProtoType *FPT =
6752 NewFD->getType()->castAs<FunctionProtoType>();
6753 QualType Result = SubstAutoType(FPT->getResultType(),
6754 Context.DependentTy);
6755 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6756 FPT->getExtProtoInfo()));
6757 }
6758
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006759 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006760 // The inline specifier shall not appear on a block scope function
6761 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006762 if (isInline && !NewFD->isInvalidDecl()) {
6763 if (CurContext->isFunctionOrMethod()) {
6764 // 'inline' is not allowed on block scope function declaration.
6765 Diag(D.getDeclSpec().getInlineSpecLoc(),
6766 diag::err_inline_declaration_block_scope) << Name
6767 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6768 }
6769 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006770
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006771 // C++ [dcl.fct.spec]p6:
6772 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006773 // constructor or conversion function within its class definition;
6774 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006775 if (isExplicit && !NewFD->isInvalidDecl()) {
6776 if (!CurContext->isRecord()) {
6777 // 'explicit' was specified outside of the class.
6778 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6779 diag::err_explicit_out_of_class)
6780 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6781 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6782 !isa<CXXConversionDecl>(NewFD)) {
6783 // 'explicit' was specified on a function that wasn't a constructor
6784 // or conversion function.
6785 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6786 diag::err_explicit_non_ctor_or_conv_function)
6787 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6788 }
6789 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006790
Richard Smitha77a0a62011-08-15 21:04:07 +00006791 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006792 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006793 // are implicitly inline.
6794 NewFD->setImplicitlyInline();
6795
Richard Smith574f4f62013-01-14 05:37:29 +00006796 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006797 // be either constructors or to return a literal type. Therefore,
6798 // destructors cannot be declared constexpr.
6799 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006800 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006801 }
6802
Douglas Gregor26701a42011-09-09 02:06:17 +00006803 // If __module_private__ was specified, mark the function accordingly.
6804 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006805 if (isFunctionTemplateSpecialization) {
6806 SourceLocation ModulePrivateLoc
6807 = D.getDeclSpec().getModulePrivateSpecLoc();
6808 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6809 << 0
6810 << FixItHint::CreateRemoval(ModulePrivateLoc);
6811 } else {
6812 NewFD->setModulePrivate();
6813 if (FunctionTemplate)
6814 FunctionTemplate->setModulePrivate();
6815 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006816 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006817
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006818 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006819 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006820 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006821 FunctionTemplate->setAccess(AS_public);
6822 }
Richard Smith64017682013-07-17 23:53:16 +00006823 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006824 NewFD->setAccess(AS_public);
6825 }
6826
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006827 // If a function is defined as defaulted or deleted, mark it as such now.
6828 switch (D.getFunctionDefinitionKind()) {
6829 case FDK_Declaration:
6830 case FDK_Definition:
6831 break;
6832
6833 case FDK_Defaulted:
6834 NewFD->setDefaulted();
6835 break;
6836
6837 case FDK_Deleted:
6838 NewFD->setDeletedAsWritten();
6839 break;
6840 }
6841
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006842 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6843 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006844 // C++ [class.mfct]p2:
6845 // A member function may be defined (8.4) in its class definition, in
6846 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006847 NewFD->setImplicitlyInline();
6848 }
6849
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006850 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6851 !CurContext->isRecord()) {
6852 // C++ [class.static]p1:
6853 // A data or function member of a class may be declared static
6854 // in a class definition, in which case it is a static member of
6855 // the class.
6856
6857 // Complain about the 'static' specifier if it's on an out-of-line
6858 // member function definition.
6859 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6860 diag::err_static_out_of_line)
6861 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6862 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006863
6864 // C++11 [except.spec]p15:
6865 // A deallocation function with no exception-specification is treated
6866 // as if it were specified with noexcept(true).
6867 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6868 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6869 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006870 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006871 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6872 EPI.ExceptionSpecType = EST_BasicNoexcept;
6873 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00006874 FPT->getArgTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006875 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006876 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006877
6878 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006879 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006880 isExplicitSpecialization ||
6881 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006882
Zhongxing Xubece5d62009-01-16 01:13:29 +00006883 // Handle GNU asm-label extension (encoded as an attribute).
6884 if (Expr *E = (Expr*) D.getAsmLabel()) {
6885 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006886 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006887 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6888 SE->getString()));
David Chisnall0867d9c2012-02-18 16:12:34 +00006889 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6890 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6891 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6892 if (I != ExtnameUndeclaredIdentifiers.end()) {
6893 NewFD->addAttr(I->second);
6894 ExtnameUndeclaredIdentifiers.erase(I);
6895 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006896 }
6897
Chris Lattner9af40c12009-04-25 06:12:16 +00006898 // Copy the parameter declarations from the declarator D to the function
6899 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006900 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006901 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006902 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006903
Zhongxing Xubece5d62009-01-16 01:13:29 +00006904 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6905 // function that takes no arguments, not a function that takes a
6906 // single void argument.
6907 // We let through "const void" here because Sema::GetTypeForDeclarator
6908 // already checks for that case.
6909 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6910 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006911 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00006912 // Empty arg list, don't push any params.
Eli Friedman8f5e9832012-09-20 01:40:23 +00006913 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xubece5d62009-01-16 01:13:29 +00006914 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006915 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00006916 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006917 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6918 Param->setDeclContext(NewFD);
6919 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00006920
6921 if (Param->isInvalidDecl())
6922 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006923 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006924 }
Mike Stump11289f42009-09-09 15:08:12 +00006925
John McCall9dd450b2009-09-21 23:43:11 +00006926 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00006927 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00006928 // following example, we'll need to synthesize (unnamed)
6929 // parameters for use in the declaration.
6930 //
6931 // @code
6932 // typedef void fn(int);
6933 // fn f;
6934 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00006935
Chris Lattner47c0d002009-04-25 06:03:53 +00006936 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00006937 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6938 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00006939 ParmVarDecl *Param =
6940 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00006941 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00006942 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006943 }
Chris Lattner49303b22009-04-25 18:38:18 +00006944 } else {
6945 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6946 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00006947 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00006948
Chris Lattner9af40c12009-04-25 06:12:16 +00006949 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00006950 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00006951
James Molloy6f8780b2012-02-29 10:24:19 +00006952 // Find all anonymous symbols defined during the declaration of this function
6953 // and add to NewFD. This lets us track decls such 'enum Y' in:
6954 //
6955 // void f(enum Y {AA} x) {}
6956 //
6957 // which would otherwise incorrectly end up in the translation unit scope.
6958 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6959 DeclsInPrototypeScope.clear();
6960
Richard Smithdebc59d2013-01-30 05:45:05 +00006961 if (D.getDeclSpec().isNoreturnSpecified())
6962 NewFD->addAttr(
6963 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6964 Context));
6965
Richard Smith84208dc2012-03-13 05:56:40 +00006966 // Functions returning a variably modified type violate C99 6.7.5.2p2
6967 // because all functions have linkage.
6968 if (!NewFD->isInvalidDecl() &&
6969 NewFD->getResultType()->isVariablyModifiedType()) {
6970 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6971 NewFD->setInvalidDecl();
6972 }
6973
Rafael Espindolac67f2232012-05-10 02:50:16 +00006974 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00006975 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00006976
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006977 QualType RetType = NewFD->getResultType();
6978 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6979 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6980 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6981 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006982 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramer9940a5d2013-10-16 16:21:04 +00006983 // Attach the attribute to the new decl. Don't apply the attribute if it
6984 // returns an instance of the class (e.g. assignment operators).
6985 if (!MD || MD->getParent() != Ret) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006986 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6987 Context));
6988 }
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006989 }
6990
David Blaikiebbafb8a2012-03-11 07:00:24 +00006991 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006992 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00006993 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00006994 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6995 CheckMain(NewFD, D.getDeclSpec());
6996
David Majnemerc729b0b2013-09-16 22:44:20 +00006997 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6998 CheckMSVCRTEntryPoint(NewFD);
6999
David Majnemer027f9c42013-07-06 02:13:46 +00007000 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00007001 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7002 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00007003 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007004 // Make graceful recovery from an invalid redeclaration.
7005 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007006 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007007 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7008 "previous declaration set still overloaded");
7009 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007010 // C++11 [replacement.functions]p3:
7011 // The program's definitions shall not be specified as inline.
7012 //
7013 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7014 //
7015 // Suppress the diagnostic if the function is __attribute__((used)), since
7016 // that forces an external definition to be emitted.
7017 if (D.getDeclSpec().isInlineSpecified() &&
7018 NewFD->isReplaceableGlobalAllocationFunction() &&
7019 !NewFD->hasAttr<UsedAttr>())
7020 Diag(D.getDeclSpec().getInlineSpecLoc(),
7021 diag::ext_operator_new_delete_declared_inline)
7022 << NewFD->getDeclName();
7023
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007024 // If the declarator is a template-id, translate the parser's template
7025 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007026 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7027 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7028 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7029 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007030 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007031 TemplateId->NumArgs);
7032 translateTemplateArguments(TemplateArgsPtr,
7033 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007034
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007035 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007036
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007037 if (NewFD->isInvalidDecl()) {
7038 HasExplicitTemplateArgs = false;
7039 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007040 // Function template with explicit template arguments.
7041 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7042 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7043
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007044 HasExplicitTemplateArgs = false;
7045 } else if (!isFunctionTemplateSpecialization &&
7046 !D.getDeclSpec().isFriendSpecified()) {
7047 // We have encountered something that the user meant to be a
7048 // specialization (because it has explicitly-specified template
7049 // arguments) but that was not introduced with a "template<>" (or had
7050 // too few of them).
Larisse Voufo39a1e502013-08-06 01:03:05 +00007051 // FIXME: Differentiate between attempts for explicit instantiations
7052 // (starting with "template") and the rest.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007053 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7054 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7055 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007056 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00007057 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007058 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00007059 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007060 // "friend void foo<>(int);" is an implicit specialization decl.
7061 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007062 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007063 } else if (isFriend && isFunctionTemplateSpecialization) {
7064 // This combination is only possible in a recovery case; the user
7065 // wrote something like:
7066 // template <> friend void foo(int);
7067 // which we're recovering from as if the user had written:
7068 // friend void foo<>(int);
7069 // Go ahead and fake up a template id.
7070 HasExplicitTemplateArgs = true;
7071 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7072 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007073 }
John McCallf7cfb222010-10-13 05:45:15 +00007074
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007075 // If it's a friend (and only if it's a friend), it's possible
7076 // that either the specialized function type or the specialized
7077 // template is dependent, and therefore matching will fail. In
7078 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007079 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007080 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007081 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7082 TemplateSpecializationType::anyDependentTemplateArguments(
7083 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7084 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007085 assert(HasExplicitTemplateArgs &&
7086 "friend function specialization without template args");
7087 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7088 Previous))
7089 NewFD->setInvalidDecl();
7090 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007091 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007092 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007093 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007094 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007095 diag::ext_function_specialization_in_class :
7096 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007097 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007098 } else if (CheckFunctionTemplateSpecialization(NewFD,
7099 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7100 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007101 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007102
7103 // C++ [dcl.stc]p1:
7104 // A storage-class-specifier shall not be specified in an explicit
7105 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007106 FunctionTemplateSpecializationInfo *Info =
7107 NewFD->getTemplateSpecializationInfo();
7108 if (Info && SC != SC_None) {
7109 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007110 Diag(NewFD->getLocation(),
7111 diag::err_explicit_specialization_inconsistent_storage_class)
7112 << SC
7113 << FixItHint::CreateRemoval(
7114 D.getDeclSpec().getStorageClassSpecLoc());
7115
7116 else
7117 Diag(NewFD->getLocation(),
7118 diag::ext_explicit_specialization_storage_class)
7119 << FixItHint::CreateRemoval(
7120 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007121 }
7122
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007123 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7124 if (CheckMemberSpecialization(NewFD, Previous))
7125 NewFD->setInvalidDecl();
7126 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007127
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007128 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007129 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007130 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7131 CheckMain(NewFD, D.getDeclSpec());
7132
David Majnemerc729b0b2013-09-16 22:44:20 +00007133 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7134 CheckMSVCRTEntryPoint(NewFD);
7135
David Blaikied937bf12011-09-08 06:33:04 +00007136 if (NewFD->isInvalidDecl()) {
7137 // If this is a class member, mark the class invalid immediately.
7138 // This avoids some consistency errors later.
7139 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7140 methodDecl->getParent()->setInvalidDecl();
David Majnemer027f9c42013-07-06 02:13:46 +00007141 } else
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007142 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7143 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007144 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007145
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007146 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007147 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7148 "previous declaration set still overloaded");
7149
7150 NamedDecl *PrincipalDecl = (FunctionTemplate
7151 ? cast<NamedDecl>(FunctionTemplate)
7152 : NewFD);
7153
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007154 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007155 AccessSpecifier Access = AS_public;
7156 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007157 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007158
7159 NewFD->setAccess(Access);
7160 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007161 }
7162
7163 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7164 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7165 PrincipalDecl->setNonMemberOperator();
7166
7167 // If we have a function template, check the template parameter
7168 // list. This will check and merge default template arguments.
7169 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007170 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007171 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007172 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00007173 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007174 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007175 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007176 ? TPC_FriendFunctionTemplateDefinition
7177 : TPC_FriendFunctionTemplate)
7178 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007179 DC && DC->isRecord() &&
7180 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007181 ? TPC_ClassTemplateMember
7182 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007183 }
7184
7185 if (NewFD->isInvalidDecl()) {
7186 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007187 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007188 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007189 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007190 // Fake up an access specifier if it's supposed to be a class member.
7191 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7192 NewFD->setAccess(AS_public);
7193
7194 // Qualified decls generally require a previous declaration.
7195 if (D.getCXXScopeSpec().isSet()) {
7196 // ...with the major exception of templated-scope or
7197 // dependent-scope friend declarations.
7198
7199 // TODO: we currently also suppress this check in dependent
7200 // contexts because (1) the parameter depth will be off when
7201 // matching friend templates and (2) we might actually be
7202 // selecting a friend based on a dependent factor. But there
7203 // are situations where these conditions don't apply and we
7204 // can actually do this check immediately.
7205 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007206 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007207 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7208 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007209 // ignore these
7210 } else {
7211 // The user tried to provide an out-of-line definition for a
7212 // function that is a member of a class or namespace, but there
7213 // was no such member function declared (C++ [class.mfct]p2,
7214 // C++ [namespace.memdef]p2). For example:
7215 //
7216 // class X {
7217 // void f() const;
7218 // };
7219 //
7220 // void X::f() { } // ill-formed
7221 //
7222 // Complain about this problem, and attempt to suggest close
7223 // matches (e.g., those that differ only in cv-qualifiers and
7224 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007225
Richard Smith114394f2013-08-09 04:35:01 +00007226 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7227 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007228 AddToScope = ExtraArgs.AddToScope;
7229 return Result;
7230 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007231 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007232
7233 // Unqualified local friend declarations are required to resolve
7234 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007235 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007236 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7237 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007238 AddToScope = ExtraArgs.AddToScope;
7239 return Result;
7240 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007241 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007242
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007243 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007244 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007245 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007246 // An out-of-line member function declaration must also be a
7247 // definition (C++ [dcl.meaning]p1).
7248 // Note that this is not the case for explicit specializations of
7249 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007250 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7251 // extension for compatibility with old SWIG code which likes to
7252 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007253 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7254 << D.getCXXScopeSpec().getRange();
7255 }
7256 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007257
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007258 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007259 checkAttributesAfterMerging(*this, *NewFD);
7260
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007261 AddKnownFunctionAttributes(NewFD);
7262
Douglas Gregor72609052010-08-06 13:50:58 +00007263 if (NewFD->hasAttr<OverloadableAttr>() &&
7264 !NewFD->getType()->getAs<FunctionProtoType>()) {
7265 Diag(NewFD->getLocation(),
7266 diag::err_attribute_overloadable_no_prototype)
7267 << NewFD;
7268
7269 // Turn this into a variadic function with no parameters.
7270 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007271 FunctionProtoType::ExtProtoInfo EPI(
7272 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007273 EPI.Variadic = true;
7274 EPI.ExtInfo = FT->getExtInfo();
7275
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007276 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007277 NewFD->setType(R);
7278 }
7279
Eli Friedman570024a2010-08-05 06:57:20 +00007280 // If there's a #pragma GCC visibility in scope, and this isn't a class
7281 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007282 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007283 AddPushedVisibilityAttribute(NewFD);
7284
John McCall32f5fe12011-09-30 05:12:12 +00007285 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7286 // marking the function.
7287 AddCFAuditedAttribute(NewFD);
7288
Richard Smithac974a32013-06-30 09:48:50 +00007289 // If this is the first declaration of an extern C variable, update
7290 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007291 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007292 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007293 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007294
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007295 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007296 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007297
David Blaikiebbafb8a2012-03-11 07:00:24 +00007298 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007299 if (FunctionTemplate) {
7300 if (NewFD->isInvalidDecl())
7301 FunctionTemplate->setInvalidDecl();
7302 return FunctionTemplate;
7303 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007304 }
Mike Stump11289f42009-09-09 15:08:12 +00007305
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007306 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007307 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7308 if ((getLangOpts().OpenCLVersion >= 120)
7309 && (SC == SC_Static)) {
7310 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7311 D.setInvalidType();
7312 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007313
7314 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7315 if (!NewFD->getResultType()->isVoidType()) {
7316 Diag(D.getIdentifierLoc(),
7317 diag::err_expected_kernel_void_return_type);
7318 D.setInvalidType();
7319 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007320
7321 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007322 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7323 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly39989da2013-01-29 10:54:06 +00007324 ParmVarDecl *Param = *PI;
Matt Arsenaultefb38192013-07-23 01:23:36 +00007325 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007326 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007327 }
7328
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007329 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007330
David Blaikiebbafb8a2012-03-11 07:00:24 +00007331 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007332 if (IdentifierInfo *II = NewFD->getIdentifier())
7333 if (!NewFD->isInvalidDecl() &&
7334 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7335 if (II->isStr("cudaConfigureCall")) {
7336 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7337 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7338
7339 Context.setcudaConfigureCallDecl(NewFD);
7340 }
7341 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007342
7343 // Here we have an function template explicit specialization at class scope.
7344 // The actually specialization will be postponed to template instatiation
7345 // time via the ClassScopeFunctionSpecializationDecl node.
7346 if (isDependentClassScopeExplicitSpecialization) {
7347 ClassScopeFunctionSpecializationDecl *NewSpec =
7348 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007349 Context, CurContext, SourceLocation(),
7350 cast<CXXMethodDecl>(NewFD),
7351 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007352 CurContext->addDecl(NewSpec);
7353 AddToScope = false;
7354 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007355
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007356 return NewFD;
7357}
7358
7359/// \brief Perform semantic checking of a new function declaration.
7360///
7361/// Performs semantic analysis of the new function declaration
7362/// NewFD. This routine performs all semantic checking that does not
7363/// require the actual declarator involved in the declaration, and is
7364/// used both for the declaration of functions as they are parsed
7365/// (called via ActOnDeclarator) and for the declaration of functions
7366/// that have been instantiated via C++ template instantiation (called
7367/// via InstantiateDecl).
7368///
James Dennettffad8b72012-06-22 08:10:18 +00007369/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007370/// an explicit specialization of the previous declaration.
7371///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007372/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007373///
James Dennettffad8b72012-06-22 08:10:18 +00007374/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007375bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007376 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007377 bool IsExplicitSpecialization) {
David Blaikied937bf12011-09-08 06:33:04 +00007378 assert(!NewFD->getResultType()->isVariablyModifiedType()
7379 && "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007380
Richard Smith1c34fb72013-08-13 18:18:50 +00007381 // Determine whether the type of this function should be merged with
7382 // a previous visible declaration. This never happens for functions in C++,
7383 // and always happens in C if the previous declaration was visible.
7384 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7385 !Previous.isShadowed();
7386
Douglas Gregor3552dab2013-01-09 00:47:56 +00007387 // Filter out any non-conflicting previous declarations.
7388 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7389
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007390 bool Redeclaration = false;
Richard Smith574f4f62013-01-14 05:37:29 +00007391 NamedDecl *OldDecl = 0;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007392
Douglas Gregore62c0a42009-02-24 01:23:02 +00007393 // Merge or overload the declaration with an existing declaration of
7394 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007395 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007396 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007397 // a declaration that requires merging. If it's an overload,
7398 // there's no more work to do here; we'll just add the new
7399 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007400 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007401 NamedDecl *Candidate = Previous.getFoundDecl();
7402 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7403 Redeclaration = true;
7404 OldDecl = Candidate;
7405 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007406 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007407 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7408 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007409 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007410 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007411 break;
7412
7413 case Ovl_NonFunction:
7414 Redeclaration = true;
7415 break;
7416
7417 case Ovl_Overload:
7418 Redeclaration = false;
7419 break;
John McCall1f82f242009-11-18 22:49:29 +00007420 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007421
David Blaikiebbafb8a2012-03-11 07:00:24 +00007422 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007423 // If a function name is overloadable in C, then every function
7424 // with that name must be marked "overloadable".
7425 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7426 << Redeclaration << NewFD;
7427 NamedDecl *OverloadedDecl = 0;
7428 if (Redeclaration)
7429 OverloadedDecl = OldDecl;
7430 else if (!Previous.empty())
7431 OverloadedDecl = Previous.getRepresentativeDecl();
7432 if (OverloadedDecl)
7433 Diag(OverloadedDecl->getLocation(),
7434 diag::note_attribute_overloadable_prev_overload);
7435 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7436 Context));
7437 }
John McCall1f82f242009-11-18 22:49:29 +00007438 }
Richard Smith574f4f62013-01-14 05:37:29 +00007439 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007440
Richard Smithac974a32013-06-30 09:48:50 +00007441 // Check for a previous extern "C" declaration with this name.
7442 if (!Redeclaration &&
7443 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7444 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7445 if (!Previous.empty()) {
7446 // This is an extern "C" declaration with the same name as a previous
7447 // declaration, and thus redeclares that entity...
7448 Redeclaration = true;
7449 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007450 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007451
7452 // ... except in the presence of __attribute__((overloadable)).
7453 if (OldDecl->hasAttr<OverloadableAttr>()) {
7454 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7455 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7456 << Redeclaration << NewFD;
7457 Diag(Previous.getFoundDecl()->getLocation(),
7458 diag::note_attribute_overloadable_prev_overload);
7459 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7460 Context));
7461 }
7462 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7463 Redeclaration = false;
7464 OldDecl = 0;
7465 }
7466 }
7467 }
7468 }
7469
Richard Smith574f4f62013-01-14 05:37:29 +00007470 // C++11 [dcl.constexpr]p8:
7471 // A constexpr specifier for a non-static member function that is not
7472 // a constructor declares that member function to be const.
7473 //
7474 // This needs to be delayed until we know whether this is an out-of-line
7475 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007476 //
7477 // This rule is not present in C++1y, so we produce a backwards
7478 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007479 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007480 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7481 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007482 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7483 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7484 if (FunctionTemplateDecl *OldTD =
7485 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7486 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7487 if (!OldMD || !OldMD->isStatic()) {
7488 const FunctionProtoType *FPT =
7489 MD->getType()->castAs<FunctionProtoType>();
7490 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7491 EPI.TypeQuals |= Qualifiers::Const;
7492 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00007493 FPT->getArgTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007494
7495 // Warn that we did this, if we're not performing template instantiation.
7496 // In that case, we'll have warned already when the template was defined.
7497 if (ActiveTemplateInstantiations.empty()) {
7498 SourceLocation AddConstLoc;
7499 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7500 .IgnoreParens().getAs<FunctionTypeLoc>())
7501 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7502
7503 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7504 << FixItHint::CreateInsertion(AddConstLoc, " const");
7505 }
Richard Smith574f4f62013-01-14 05:37:29 +00007506 }
7507 }
7508
7509 if (Redeclaration) {
7510 // NewFD and OldDecl represent declarations that need to be
7511 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007512 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007513 NewFD->setInvalidDecl();
7514 return Redeclaration;
7515 }
7516
7517 Previous.clear();
7518 Previous.addDecl(OldDecl);
7519
7520 if (FunctionTemplateDecl *OldTemplateDecl
7521 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7522 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7523 FunctionTemplateDecl *NewTemplateDecl
7524 = NewFD->getDescribedFunctionTemplate();
7525 assert(NewTemplateDecl && "Template/non-template mismatch");
7526 if (CXXMethodDecl *Method
7527 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7528 Method->setAccess(OldTemplateDecl->getAccess());
7529 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007530 }
Richard Smith574f4f62013-01-14 05:37:29 +00007531
7532 // If this is an explicit specialization of a member that is a function
7533 // template, mark it as a member specialization.
7534 if (IsExplicitSpecialization &&
7535 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7536 NewTemplateDecl->setMemberSpecialization();
7537 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007538 }
Richard Smith574f4f62013-01-14 05:37:29 +00007539
7540 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007541 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007542 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007543
7544 if (isa<CXXMethodDecl>(NewFD)) {
7545 // A valid redeclaration of a C++ method must be out-of-line,
7546 // but (unfortunately) it's not necessarily a definition
7547 // because of templates, which means that the previous
7548 // declaration is not necessarily from the class definition.
7549
7550 // For just setting the access, that doesn't matter.
7551 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7552 NewFD->setAccess(oldMethod->getAccess());
7553
7554 // Update the key-function state if necessary for this ABI.
7555 if (NewFD->isInlined() &&
7556 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7557 // setNonKeyFunction needs to work with the original
7558 // declaration from the class definition, and isVirtual() is
7559 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007560 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007561 if (oldMethod->isVirtual()) {
7562 Context.setNonKeyFunction(oldMethod);
7563 }
7564 }
7565 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007566 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007567 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007568
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007569 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007570 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007571 // C++-specific checks.
7572 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7573 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007574 } else if (CXXDestructorDecl *Destructor =
7575 dyn_cast<CXXDestructorDecl>(NewFD)) {
7576 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007577 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007578
Douglas Gregor7454c562010-07-02 20:37:36 +00007579 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007580 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007581 if (!ClassType->isDependentType()) {
7582 DeclarationName Name
7583 = Context.DeclarationNames.getCXXDestructorName(
7584 Context.getCanonicalType(ClassType));
7585 if (NewFD->getDeclName() != Name) {
7586 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007587 NewFD->setInvalidDecl();
7588 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007589 }
7590 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007591 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007592 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007593 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007594 }
7595
7596 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007597 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7598 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007599 !Method->getDescribedFunctionTemplate() &&
7600 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007601 if (AddOverriddenMethods(Method->getParent(), Method)) {
7602 // If the function was marked as "static", we have a problem.
7603 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007604 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007605 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007606 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007607 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007608
7609 if (Method->isStatic())
7610 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007611 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007612
7613 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7614 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007615 CheckOverloadedOperatorDeclaration(NewFD)) {
7616 NewFD->setInvalidDecl();
7617 return Redeclaration;
7618 }
Alexis Huntc88db062010-01-13 09:01:02 +00007619
7620 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7621 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007622 CheckLiteralOperatorDeclaration(NewFD)) {
7623 NewFD->setInvalidDecl();
7624 return Redeclaration;
7625 }
Alexis Huntc88db062010-01-13 09:01:02 +00007626
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007627 // In C++, check default arguments now that we have merged decls. Unless
7628 // the lexical context is the class, because in this case this is done
7629 // during delayed parsing anyway.
7630 if (!CurContext->isRecord())
7631 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007632
Douglas Gregor9246b682010-12-21 19:47:46 +00007633 // If this function declares a builtin function, check the type of this
7634 // declaration against the expected type for the builtin.
7635 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7636 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007637 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007638 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7639 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7640 // The type of this function differs from the type of the builtin,
7641 // so forget about the builtin entirely.
7642 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7643 }
7644 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007645
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007646 // If this function is declared as being extern "C", then check to see if
7647 // the function returns a UDT (class, struct, or union type) that is not C
7648 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007649 // But, issue any diagnostic on the first declaration only.
7650 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007651 QualType R = NewFD->getResultType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007652 if (R->isIncompleteType() && !R->isVoidType())
7653 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7654 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007655 else if (!R.isPODType(Context) && !R->isVoidType() &&
7656 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007657 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007658 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007659 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007660 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007661}
7662
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007663static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7664 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7665 if (!TSI)
7666 return SourceRange();
7667
7668 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007669 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007670 if (!FunctionTL)
7671 return SourceRange();
7672
David Blaikie6adc78e2013-02-18 22:06:02 +00007673 TypeLoc ResultTL = FunctionTL.getResultLoc();
7674 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007675 return ResultTL.getSourceRange();
7676
7677 return SourceRange();
7678}
7679
David Blaikied937bf12011-09-08 06:33:04 +00007680void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smith3f333f22012-02-04 06:10:17 +00007681 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7682 // static or constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007683 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7684 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007685 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007686 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007687 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007688 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007689 ? diag::err_static_main : diag::warn_static_main)
7690 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7691 if (FD->isInlineSpecified())
7692 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7693 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007694 if (DS.isNoreturnSpecified()) {
7695 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7696 SourceRange NoreturnRange(NoreturnLoc,
7697 PP.getLocForEndOfToken(NoreturnLoc));
7698 Diag(NoreturnLoc, diag::ext_noreturn_main);
7699 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7700 << FixItHint::CreateRemoval(NoreturnRange);
7701 }
Richard Smith3f333f22012-02-04 06:10:17 +00007702 if (FD->isConstexpr()) {
7703 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7704 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7705 FD->setConstexpr(false);
7706 }
John McCall02dee0a2009-07-25 04:36:53 +00007707
Joey Goulya7310a82013-11-05 12:30:39 +00007708 if (getLangOpts().OpenCL) {
7709 Diag(FD->getLocation(), diag::err_opencl_no_main)
7710 << FD->hasAttr<OpenCLKernelAttr>();
7711 FD->setInvalidDecl();
7712 return;
7713 }
7714
John McCall02dee0a2009-07-25 04:36:53 +00007715 QualType T = FD->getType();
7716 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007717 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007718
John McCall5ed3caf2012-02-14 19:50:52 +00007719 // All the standards say that main() should should return 'int'.
7720 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7721 // In C and C++, main magically returns 0 if you fall off the end;
7722 // set the flag which tells us that.
7723 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7724 FD->setHasImplicitReturnZero(true);
7725
7726 // In C with GNU extensions we allow main() to have non-integer return
7727 // type, but we should warn about the extension, and we disable the
7728 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007729 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007730 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7731
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007732 SourceRange ResultRange = getResultSourceRange(FD);
7733 if (ResultRange.isValid())
7734 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7735 << FixItHint::CreateReplacement(ResultRange, "int");
7736
John McCall5ed3caf2012-02-14 19:50:52 +00007737 // Otherwise, this is just a flat-out error.
7738 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007739 SourceRange ResultRange = getResultSourceRange(FD);
7740 if (ResultRange.isValid())
7741 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7742 << FixItHint::CreateReplacement(ResultRange, "int");
7743 else
7744 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7745
John McCall02dee0a2009-07-25 04:36:53 +00007746 FD->setInvalidDecl(true);
7747 }
7748
7749 // Treat protoless main() as nullary.
7750 if (isa<FunctionNoProtoType>(FT)) return;
7751
7752 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7753 unsigned nparams = FTP->getNumArgs();
7754 assert(FD->getNumParams() == nparams);
7755
John McCall0e21fcc2009-12-24 09:58:38 +00007756 bool HasExtraParameters = (nparams > 3);
7757
7758 // Darwin passes an undocumented fourth argument of type char**. If
7759 // other platforms start sprouting these, the logic below will start
7760 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007761 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007762 HasExtraParameters = false;
7763
7764 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007765 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7766 FD->setInvalidDecl(true);
7767 nparams = 3;
7768 }
7769
7770 // FIXME: a lot of the following diagnostics would be improved
7771 // if we had some location information about types.
7772
7773 QualType CharPP =
7774 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007775 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007776
7777 for (unsigned i = 0; i < nparams; ++i) {
7778 QualType AT = FTP->getArgType(i);
7779
7780 bool mismatch = true;
7781
7782 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7783 mismatch = false;
7784 else if (Expected[i] == CharPP) {
7785 // As an extension, the following forms are okay:
7786 // char const **
7787 // char const * const *
7788 // char * const *
7789
John McCall8ccfcb52009-09-24 19:53:00 +00007790 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007791 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007792 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7793 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007794 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7795 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007796 qs.removeConst();
7797 mismatch = !qs.empty();
7798 }
7799 }
7800
7801 if (mismatch) {
7802 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7803 // TODO: suggest replacing given type with expected type
7804 FD->setInvalidDecl(true);
7805 }
7806 }
7807
7808 if (nparams == 1 && !FD->isInvalidDecl()) {
7809 Diag(FD->getLocation(), diag::warn_main_one_arg);
7810 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007811
7812 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
David Majnemerc729b0b2013-09-16 22:44:20 +00007813 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7814 FD->setInvalidDecl();
7815 }
7816}
7817
7818void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7819 QualType T = FD->getType();
7820 assert(T->isFunctionType() && "function decl is not of function type");
7821 const FunctionType *FT = T->castAs<FunctionType>();
7822
7823 // Set an implicit return of 'zero' if the function can return some integral,
7824 // enumeration, pointer or nullptr type.
7825 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7826 FT->getResultType()->isAnyPointerType() ||
7827 FT->getResultType()->isNullPtrType())
7828 // DllMain is exempt because a return value of zero means it failed.
7829 if (FD->getName() != "DllMain")
7830 FD->setHasImplicitReturnZero(true);
7831
7832 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7833 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
Douglas Gregorbff62032010-10-21 16:57:46 +00007834 FD->setInvalidDecl();
7835 }
John McCalld9baf6a2009-07-24 03:03:21 +00007836}
7837
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007838bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007839 // FIXME: Need strict checking. In C89, we need to check for
7840 // any assignment, increment, decrement, function-calls, or
7841 // commas outside of a sizeof. In C99, it's the same list,
7842 // except that the aforementioned are allowed in unevaluated
7843 // expressions. Everything else falls under the
7844 // "may accept other forms of constant expressions" exception.
7845 // (We never end up here for C++, so the constant expression
7846 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007847 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007848 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007849 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7850 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007851 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007852}
7853
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007854namespace {
7855 // Visits an initialization expression to see if OrigDecl is evaluated in
7856 // its own initialization and throws a warning if it does.
7857 class SelfReferenceChecker
7858 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7859 Sema &S;
7860 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007861 bool isRecordType;
7862 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007863 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007864
7865 public:
7866 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7867
7868 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007869 S(S), OrigDecl(OrigDecl) {
7870 isPODType = false;
7871 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007872 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007873 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7874 isPODType = VD->getType().isPODType(S.Context);
7875 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007876 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007877 }
7878 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007879
Richard Trieu64c51ab2012-05-09 00:21:34 +00007880 // For most expressions, the cast is directly above the DeclRefExpr.
7881 // For conditional operators, the cast can be outside the conditional
7882 // operator if both expressions are DeclRefExpr's.
7883 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007884 if (isReferenceType)
7885 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007886 E = E->IgnoreParenImpCasts();
7887 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7888 HandleDeclRefExpr(DRE);
7889 return;
7890 }
7891
7892 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7893 HandleValue(CO->getTrueExpr());
7894 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007895 return;
7896 }
7897
7898 if (isa<MemberExpr>(E)) {
7899 Expr *Base = E->IgnoreParenImpCasts();
7900 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7901 // Check for static member variables and don't warn on them.
7902 if (!isa<FieldDecl>(ME->getMemberDecl()))
7903 return;
7904 Base = ME->getBase()->IgnoreParenImpCasts();
7905 }
7906 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7907 HandleDeclRefExpr(DRE);
7908 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007909 }
7910 }
7911
Richard Trieu32673472012-10-01 17:39:51 +00007912 // Reference types are handled here since all uses of references are
7913 // bad, not just r-value uses.
7914 void VisitDeclRefExpr(DeclRefExpr *E) {
7915 if (isReferenceType)
7916 HandleDeclRefExpr(E);
7917 }
7918
Richard Trieu64c51ab2012-05-09 00:21:34 +00007919 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00007920 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00007921 (isRecordType && E->getCastKind() == CK_NoOp))
7922 HandleValue(E->getSubExpr());
7923
7924 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007925 }
7926
Richard Trieua04ad1a2011-09-01 21:44:13 +00007927 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00007928 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00007929 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007930
Richard Trieu742c6ed2012-10-03 00:41:36 +00007931 // Warn when a non-static method call is followed by non-static member
7932 // field accesses, which is followed by a DeclRefExpr.
7933 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7934 bool Warn = (MD && !MD->isStatic());
7935 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7936 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7937 if (!isa<FieldDecl>(ME->getMemberDecl()))
7938 Warn = false;
7939 Base = ME->getBase()->IgnoreParenImpCasts();
7940 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007941
Richard Trieu742c6ed2012-10-03 00:41:36 +00007942 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7943 if (Warn)
7944 HandleDeclRefExpr(DRE);
7945 return;
7946 }
7947
7948 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7949 // Visit that expression.
7950 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007951 }
7952
Richard Trieu8fbd91d2013-03-26 03:41:40 +00007953 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7954 if (E->getNumArgs() > 0)
7955 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7956 HandleDeclRefExpr(DRE);
7957
7958 Inherited::VisitCXXOperatorCallExpr(E);
7959 }
7960
Richard Trieua04ad1a2011-09-01 21:44:13 +00007961 void VisitUnaryOperator(UnaryOperator *E) {
7962 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00007963 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7964 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7965 if (!isPODType)
7966 HandleValue(E->getSubExpr());
7967 return;
7968 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007969 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00007970 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00007971
7972 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7973
Richard Trieua04ad1a2011-09-01 21:44:13 +00007974 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00007975 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007976 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00007977 unsigned diag;
7978 if (isReferenceType) {
7979 diag = diag::warn_uninit_self_reference_in_reference_init;
7980 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7981 diag = diag::warn_static_self_reference_in_init;
7982 } else {
7983 diag = diag::warn_uninit_self_reference_in_init;
7984 }
7985
Richard Trieua04ad1a2011-09-01 21:44:13 +00007986 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00007987 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00007988 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007989 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00007990 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007991 }
7992 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007993
Richard Trieu32673472012-10-01 17:39:51 +00007994 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7995 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7996 bool DirectInit) {
7997 // Parameters arguments are occassionially constructed with itself,
7998 // for instance, in recursive functions. Skip them.
7999 if (isa<ParmVarDecl>(OrigDecl))
8000 return;
8001
8002 E = E->IgnoreParens();
8003
8004 // Skip checking T a = a where T is not a record or reference type.
8005 // Doing so is a way to silence uninitialized warnings.
8006 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8007 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8008 if (ICE->getCastKind() == CK_LValueToRValue)
8009 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8010 if (DRE->getDecl() == OrigDecl)
8011 return;
8012
8013 SelfReferenceChecker(S, OrigDecl).Visit(E);
8014 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008015}
8016
Douglas Gregor5fb53972009-01-14 15:45:31 +00008017/// AddInitializerToDecl - Adds the initializer Init to the
8018/// declaration dcl. If DirectInit is true, this is C++ direct
8019/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008020void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8021 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008022 // If there is no declaration, there was an error parsing it. Just ignore
8023 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008024 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008025 return;
Mike Stump11289f42009-09-09 15:08:12 +00008026
Douglas Gregor0c880302009-03-11 23:00:04 +00008027 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8028 // With declarators parsed the way they are, the parser cannot
8029 // distinguish between a normal initializer and a pure-specifier.
8030 // Thus this grotesque test.
8031 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008032 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008033 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8034 CheckPureMethod(Method, Init->getSourceRange());
8035 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008036 Diag(Method->getLocation(), diag::err_member_function_initialization)
8037 << Method->getDeclName() << Init->getSourceRange();
8038 Method->setInvalidDecl();
8039 }
8040 return;
8041 }
8042
Steve Naroff437b4d82007-09-12 20:13:48 +00008043 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8044 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008045 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8046 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008047 RealDecl->setInvalidDecl();
8048 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008049 }
Sebastian Redla9351792012-02-11 23:51:47 +00008050 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8051
Richard Smith0cc85782011-12-15 19:20:59 +00008052 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008053 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008054 Expr *DeduceInit = Init;
8055 // Initializer could be a C++ direct-initializer. Deduction only works if it
8056 // contains exactly one expression.
8057 if (CXXDirectInit) {
8058 if (CXXDirectInit->getNumExprs() == 0) {
8059 // It isn't possible to write this directly, but it is possible to
8060 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008061 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008062 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8063 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008064 << VDecl->getDeclName() << VDecl->getType()
8065 << VDecl->getSourceRange();
8066 RealDecl->setInvalidDecl();
8067 return;
8068 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008069 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008070 VDecl->isInitCapture()
8071 ? diag::err_init_capture_multiple_expressions
8072 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008073 << VDecl->getDeclName() << VDecl->getType()
8074 << VDecl->getSourceRange();
8075 RealDecl->setInvalidDecl();
8076 return;
8077 } else {
8078 DeduceInit = CXXDirectInit->getExpr(0);
8079 }
8080 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008081
8082 // Expressions default to 'id' when we're in a debugger.
8083 bool DefaultedToAuto = false;
8084 if (getLangOpts().DebuggerCastResultToId &&
8085 Init->getType() == Context.UnknownAnyTy) {
8086 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8087 if (Result.isInvalid()) {
8088 VDecl->setInvalidDecl();
8089 return;
8090 }
8091 Init = Result.take();
8092 DefaultedToAuto = true;
8093 }
Richard Smith061f1e22013-04-30 21:23:01 +00008094
8095 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008096 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008097 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008098 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008099 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008100 RealDecl->setInvalidDecl();
8101 return;
8102 }
Richard Smith061f1e22013-04-30 21:23:01 +00008103 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008104 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008105
John McCall31168b02011-06-15 23:02:42 +00008106 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008107 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008108 VDecl->setInvalidDecl();
8109
Jordan Rosed8d56692012-06-08 22:46:07 +00008110 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8111 // 'id' instead of a specific object type prevents most of our usual checks.
8112 // We only want to warn outside of template instantiations, though:
8113 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008114 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008115 DeducedType->isObjCIdType()) {
8116 SourceLocation Loc =
8117 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008118 Diag(Loc, diag::warn_auto_var_is_id)
8119 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8120 }
8121
Richard Smith30482bc2011-02-20 03:19:35 +00008122 // If this is a redeclaration, check that the type we just deduced matches
8123 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008124 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8125 // We never need to merge the type, because we cannot form an incomplete
8126 // array of auto, nor deduce such a type.
8127 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8128 }
Richard Smith27d807c2013-04-30 13:56:41 +00008129
8130 // Check the deduced type is valid for a variable declaration.
8131 CheckVariableDeclarationType(VDecl);
8132 if (VDecl->isInvalidDecl())
8133 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008134 }
Richard Smith0cc85782011-12-15 19:20:59 +00008135
8136 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8137 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8138 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8139 VDecl->setInvalidDecl();
8140 return;
8141 }
8142
Sebastian Redla9351792012-02-11 23:51:47 +00008143 if (!VDecl->getType()->isDependentType()) {
8144 // A definition must end up with a complete type, which means it must be
8145 // complete with the restriction that an array type might be completed by
8146 // the initializer; note that later code assumes this restriction.
8147 QualType BaseDeclType = VDecl->getType();
8148 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8149 BaseDeclType = Array->getElementType();
8150 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8151 diag::err_typecheck_decl_incomplete_type)) {
8152 RealDecl->setInvalidDecl();
8153 return;
8154 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008155
Sebastian Redla9351792012-02-11 23:51:47 +00008156 // The variable can not have an abstract class type.
8157 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8158 diag::err_abstract_type_in_decl,
8159 AbstractVariableType))
8160 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008161 }
8162
Sebastian Redl5ca79842010-02-01 20:16:42 +00008163 const VarDecl *Def;
8164 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008165 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008166 << VDecl->getDeclName();
8167 Diag(Def->getLocation(), diag::note_previous_definition);
8168 VDecl->setInvalidDecl();
8169 return;
8170 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008171
Douglas Gregorf0f83692010-08-24 05:27:49 +00008172 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008173 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008174 // C++ [class.static.data]p4
8175 // If a static data member is of const integral or const
8176 // enumeration type, its declaration in the class definition can
8177 // specify a constant-initializer which shall be an integral
8178 // constant expression (5.19). In that case, the member can appear
8179 // in integral constant expressions. The member shall still be
8180 // defined in a namespace scope if it is used in the program and the
8181 // namespace scope definition shall not contain an initializer.
8182 //
8183 // We already performed a redefinition check above, but for static
8184 // data members we also need to check whether there was an in-class
8185 // declaration with an initializer.
8186 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008187 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8188 << VDecl->getDeclName();
8189 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008190 return;
8191 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008192
Douglas Gregor71f39c92010-12-16 01:31:22 +00008193 if (VDecl->hasLocalStorage())
8194 getCurFunction()->setHasBranchProtectedScope();
8195
8196 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8197 VDecl->setInvalidDecl();
8198 return;
8199 }
8200 }
John McCalld4e1b762010-08-01 01:24:59 +00008201
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008202 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8203 // a kernel function cannot be initialized."
8204 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8205 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8206 VDecl->setInvalidDecl();
8207 return;
8208 }
8209
Steve Naroff61091402007-09-12 14:07:44 +00008210 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008211 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008212 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008213
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008214 // Expressions default to 'id' when we're in a debugger
8215 // and we are assigning it to a variable of Objective-C pointer type.
8216 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8217 Init->getType() == Context.UnknownAnyTy) {
8218 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8219 if (Result.isInvalid()) {
8220 VDecl->setInvalidDecl();
8221 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008222 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008223 Init = Result.take();
8224 }
Richard Smith0cc85782011-12-15 19:20:59 +00008225
8226 // Perform the initialization.
8227 if (!VDecl->isInvalidDecl()) {
8228 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8229 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008230 = DirectInit ?
8231 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8232 Init->getLocStart(),
8233 Init->getLocEnd())
8234 : InitializationKind::CreateDirectList(
8235 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008236 : InitializationKind::CreateCopy(VDecl->getLocation(),
8237 Init->getLocStart());
8238
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008239 MultiExprArg Args = Init;
8240 if (CXXDirectInit)
8241 Args = MultiExprArg(CXXDirectInit->getExprs(),
8242 CXXDirectInit->getNumExprs());
8243
8244 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8245 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008246 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008247 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008248 return;
Steve Naroff61091402007-09-12 14:07:44 +00008249 }
Richard Smith0cc85782011-12-15 19:20:59 +00008250
8251 Init = Result.takeAs<Expr>();
8252 }
8253
Richard Trieu32673472012-10-01 17:39:51 +00008254 // Check for self-references within variable initializers.
8255 // Variables declared within a function/method body (except for references)
8256 // are handled by a dataflow analysis.
8257 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8258 VDecl->getType()->isReferenceType()) {
8259 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8260 }
8261
Richard Smith0cc85782011-12-15 19:20:59 +00008262 // If the type changed, it means we had an incomplete type that was
8263 // completed by the initializer. For example:
8264 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008265 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008266 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008267 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008268
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008269 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008270 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8271
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008272 if (VDecl->hasAttr<BlocksAttr>())
8273 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008274
8275 // It is safe to assign a weak reference into a strong variable.
8276 // Although this code can still have problems:
8277 // id x = self.weakProp;
8278 // id y = self.weakProp;
8279 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8280 // paths through the function. This should be revisited if
8281 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008282 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008283 DiagnosticsEngine::Level Level =
8284 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8285 Init->getLocStart());
8286 if (Level != DiagnosticsEngine::Ignored)
8287 getCurFunction()->markSafeWeakUse(Init);
8288 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008289 }
8290
Richard Smith945f8d32013-01-14 22:39:08 +00008291 // The initialization is usually a full-expression.
8292 //
8293 // FIXME: If this is a braced initialization of an aggregate, it is not
8294 // an expression, and each individual field initializer is a separate
8295 // full-expression. For instance, in:
8296 //
8297 // struct Temp { ~Temp(); };
8298 // struct S { S(Temp); };
8299 // struct T { S a, b; } t = { Temp(), Temp() }
8300 //
8301 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008302 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8303 false,
8304 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008305 if (Result.isInvalid()) {
8306 VDecl->setInvalidDecl();
8307 return;
8308 }
8309 Init = Result.take();
8310
Richard Smith0cc85782011-12-15 19:20:59 +00008311 // Attach the initializer to the decl.
8312 VDecl->setInit(Init);
8313
8314 if (VDecl->isLocalVarDecl()) {
8315 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8316 // static storage duration shall be constant expressions or string literals.
8317 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008318 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8319 if (VDecl->getStorageClass() == SC_Static)
8320 CheckForConstantInitializer(Init, DclT);
8321 // C89 is stricter than C99 for non-static aggregate types.
8322 // C89 6.5.7p3: All the expressions [...] in an initializer list
8323 // for an object that has aggregate or union type shall be
8324 // constant expressions.
8325 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008326 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008327 !Init->isConstantInitializer(Context, false))
8328 Diag(Init->getExprLoc(),
8329 diag::ext_aggregate_init_not_constant)
8330 << Init->getSourceRange();
8331 }
Mike Stump11289f42009-09-09 15:08:12 +00008332 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008333 VDecl->getLexicalDeclContext()->isRecord()) {
8334 // This is an in-class initialization for a static data member, e.g.,
8335 //
8336 // struct S {
8337 // static const int value = 17;
8338 // };
8339
Douglas Gregor0c880302009-03-11 23:00:04 +00008340 // C++ [class.mem]p4:
8341 // A member-declarator can contain a constant-initializer only
8342 // if it declares a static member (9.4) of const integral or
8343 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008344 //
Richard Smith0cc85782011-12-15 19:20:59 +00008345 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008346 // If a non-volatile const static data member is of integral or
8347 // enumeration type, its declaration in the class definition can
8348 // specify a brace-or-equal-initializer in which every initalizer-clause
8349 // that is an assignment-expression is a constant expression. A static
8350 // data member of literal type can be declared in the class definition
8351 // with the constexpr specifier; if so, its declaration shall specify a
8352 // brace-or-equal-initializer in which every initializer-clause that is
8353 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008354
8355 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008356 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008357
Richard Smith2316cd82011-09-29 19:11:37 +00008358 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008359 // type. We separately check that every constexpr variable is of literal
8360 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008361 } else if (VDecl->isConstexpr()) {
8362
John McCalldb768922010-09-10 23:21:22 +00008363 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008364 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008365 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8366 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008367 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008368
8369 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008370 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008371 // Check whether the expression is a constant expression.
8372 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008373 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008374 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008375 // in-class initializer cannot be volatile.
8376 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8377 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008378 ; // Nothing to check.
8379 else if (Init->isIntegerConstantExpr(Context, &Loc))
8380 ; // Ok, it's an ICE!
8381 else if (Init->isEvaluatable(Context)) {
8382 // If we can constant fold the initializer through heroics, accept it,
8383 // but report this as a use of an extension for -pedantic.
8384 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8385 << Init->getSourceRange();
8386 } else {
8387 // Otherwise, this is some crazy unknown case. Report the issue at the
8388 // location provided by the isIntegerConstantExpr failed check.
8389 Diag(Loc, diag::err_in_class_initializer_non_constant)
8390 << Init->getSourceRange();
8391 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008392 }
8393
Richard Smith0cc85782011-12-15 19:20:59 +00008394 // We allow foldable floating-point constants as an extension.
8395 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008396 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8397 // it anyway and provide a fixit to add the 'constexpr'.
8398 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008399 Diag(VDecl->getLocation(),
8400 diag::ext_in_class_initializer_float_type_cxx11)
8401 << DclT << Init->getSourceRange();
8402 Diag(VDecl->getLocStart(),
8403 diag::note_in_class_initializer_float_type_cxx11)
8404 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008405 } else {
8406 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8407 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008408
Richard Smithcf656382013-01-25 04:22:16 +00008409 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8410 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8411 << Init->getSourceRange();
8412 VDecl->setInvalidDecl();
8413 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008414 }
Richard Smith256336d2011-09-29 23:18:34 +00008415
Richard Smith0cc85782011-12-15 19:20:59 +00008416 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008417 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008418 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008419 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008420 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8421 VDecl->setConstexpr(true);
8422
Richard Smith2316cd82011-09-29 19:11:37 +00008423 } else {
8424 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008425 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008426 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008427 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008428 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008429 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008430 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008431 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008432 VDecl->isExternC())) &&
8433 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008434 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008435
Richard Smith0cc85782011-12-15 19:20:59 +00008436 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008437 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008438 CheckForConstantInitializer(Init, DclT);
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008439 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8440 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8441 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smith774672e2013-04-15 08:07:34 +00008442 !Init->isConstantInitializer(
8443 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008444 // GNU C++98 edits for __thread, [basic.start.init]p4:
8445 // An object of thread storage duration shall not require dynamic
8446 // initialization.
8447 // FIXME: Need strict checking here.
8448 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8449 if (getLangOpts().CPlusPlus11)
8450 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8451 }
Steve Naroff61091402007-09-12 14:07:44 +00008452 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008453
Sebastian Redla9351792012-02-11 23:51:47 +00008454 // We will represent direct-initialization similarly to copy-initialization:
8455 // int x(1); -as-> int x = 1;
8456 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8457 //
8458 // Clients that want to distinguish between the two forms, can check for
8459 // direct initializer using VarDecl::getInitStyle().
8460 // A major benefit is that clients that don't particularly care about which
8461 // exactly form was it (like the CodeGen) can handle both cases without
8462 // special case code.
8463
8464 // C++ 8.5p11:
8465 // The form of initialization (using parentheses or '=') is generally
8466 // insignificant, but does matter when the entity being initialized has a
8467 // class type.
8468 if (CXXDirectInit) {
8469 assert(DirectInit && "Call-style initializer must be direct init.");
8470 VDecl->setInitStyle(VarDecl::CallInit);
8471 } else if (DirectInit) {
8472 // This must be list-initialization. No other way is direct-initialization.
8473 VDecl->setInitStyle(VarDecl::ListInit);
8474 }
8475
John McCall8b7fd8f12011-01-19 11:48:09 +00008476 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008477}
8478
John McCalleae5acb2010-03-31 02:13:20 +00008479/// ActOnInitializerError - Given that there was an error parsing an
8480/// initializer for the given declaration, try to return to some form
8481/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008482void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008483 // Our main concern here is re-establishing invariants like "a
8484 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008485 if (!D || D->isInvalidDecl()) return;
8486
8487 VarDecl *VD = dyn_cast<VarDecl>(D);
8488 if (!VD) return;
8489
Richard Smith30482bc2011-02-20 03:19:35 +00008490 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008491 if (ParsingInitForAutoVars.count(D)) {
8492 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008493 return;
8494 }
8495
John McCalleae5acb2010-03-31 02:13:20 +00008496 QualType Ty = VD->getType();
8497 if (Ty->isDependentType()) return;
8498
8499 // Require a complete type.
8500 if (RequireCompleteType(VD->getLocation(),
8501 Context.getBaseElementType(Ty),
8502 diag::err_typecheck_decl_incomplete_type)) {
8503 VD->setInvalidDecl();
8504 return;
8505 }
8506
8507 // Require an abstract type.
8508 if (RequireNonAbstractType(VD->getLocation(), Ty,
8509 diag::err_abstract_type_in_decl,
8510 AbstractVariableType)) {
8511 VD->setInvalidDecl();
8512 return;
8513 }
8514
8515 // Don't bother complaining about constructors or destructors,
8516 // though.
8517}
8518
John McCall48871652010-08-21 09:40:31 +00008519void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008520 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008521 // If there is no declaration, there was an error parsing it. Just ignore it.
8522 if (RealDecl == 0)
8523 return;
8524
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008525 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8526 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008527
Richard Smithf0215fe2011-12-25 21:17:58 +00008528 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008529 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008530 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8531 << Var->getDeclName() << Type;
8532 Var->setInvalidDecl();
8533 return;
8534 }
Mike Stump11289f42009-09-09 15:08:12 +00008535
Richard Smithf0215fe2011-12-25 21:17:58 +00008536 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008537 // the constexpr specifier; if so, its declaration shall specify
8538 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008539 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8540 // the definition of a variable [...] or the declaration of a static data
8541 // member.
8542 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8543 if (Var->isStaticDataMember())
8544 Diag(Var->getLocation(),
8545 diag::err_constexpr_static_mem_var_requires_init)
8546 << Var->getDeclName();
8547 else
8548 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008549 Var->setInvalidDecl();
8550 return;
8551 }
8552
Douglas Gregore6565622010-02-09 07:26:29 +00008553 switch (Var->isThisDeclarationADefinition()) {
8554 case VarDecl::Definition:
8555 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8556 break;
8557
8558 // We have an out-of-line definition of a static data member
8559 // that has an in-class initializer, so we type-check this like
8560 // a declaration.
8561 //
8562 // Fall through
8563
8564 case VarDecl::DeclarationOnly:
8565 // It's only a declaration.
8566
8567 // Block scope. C99 6.7p7: If an identifier for an object is
8568 // declared with no linkage (C99 6.2.2p6), the type for the
8569 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008570 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008571 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008572 RequireCompleteType(Var->getLocation(), Type,
8573 diag::err_typecheck_decl_incomplete_type))
8574 Var->setInvalidDecl();
8575
8576 // Make sure that the type is not abstract.
8577 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8578 RequireNonAbstractType(Var->getLocation(), Type,
8579 diag::err_abstract_type_in_decl,
8580 AbstractVariableType))
8581 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008582 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008583 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008584 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008585 Diag(Var->getLocation(), diag::note_private_extern);
8586 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008587
Douglas Gregore6565622010-02-09 07:26:29 +00008588 return;
8589
8590 case VarDecl::TentativeDefinition:
8591 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8592 // object that has file scope without an initializer, and without a
8593 // storage-class specifier or with the storage-class specifier "static",
8594 // constitutes a tentative definition. Note: A tentative definition with
8595 // external linkage is valid (C99 6.2.2p5).
8596 if (!Var->isInvalidDecl()) {
8597 if (const IncompleteArrayType *ArrayT
8598 = Context.getAsIncompleteArrayType(Type)) {
8599 if (RequireCompleteType(Var->getLocation(),
8600 ArrayT->getElementType(),
8601 diag::err_illegal_decl_array_incomplete_type))
8602 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008603 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008604 // C99 6.9.2p3: If the declaration of an identifier for an object is
8605 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8606 // declared type shall not be an incomplete type.
8607 // NOTE: code such as the following
8608 // static struct s;
8609 // struct s { int a; };
8610 // is accepted by gcc. Hence here we issue a warning instead of
8611 // an error and we do not invalidate the static declaration.
8612 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008613 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008614 RequireCompleteType(Var->getLocation(), Type,
8615 diag::ext_typecheck_decl_incomplete_type);
8616 }
8617 }
8618
8619 // Record the tentative definition; we're done.
8620 if (!Var->isInvalidDecl())
8621 TentativeDefinitions.push_back(Var);
8622 return;
8623 }
8624
8625 // Provide a specific diagnostic for uninitialized variable
8626 // definitions with incomplete array type.
8627 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008628 Diag(Var->getLocation(),
8629 diag::err_typecheck_incomplete_array_needs_initializer);
8630 Var->setInvalidDecl();
8631 return;
8632 }
8633
John McCalla755f0f2010-08-01 01:25:24 +00008634 // Provide a specific diagnostic for uninitialized variable
8635 // definitions with reference type.
8636 if (Type->isReferenceType()) {
8637 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8638 << Var->getDeclName()
8639 << SourceRange(Var->getLocation(), Var->getLocation());
8640 Var->setInvalidDecl();
8641 return;
8642 }
Douglas Gregore6565622010-02-09 07:26:29 +00008643
8644 // Do not attempt to type-check the default initializer for a
8645 // variable with dependent type.
8646 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008647 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008648
Douglas Gregore6565622010-02-09 07:26:29 +00008649 if (Var->isInvalidDecl())
8650 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008651
Douglas Gregore6565622010-02-09 07:26:29 +00008652 if (RequireCompleteType(Var->getLocation(),
8653 Context.getBaseElementType(Type),
8654 diag::err_typecheck_decl_incomplete_type)) {
8655 Var->setInvalidDecl();
8656 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008657 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008658
Douglas Gregore6565622010-02-09 07:26:29 +00008659 // The variable can not have an abstract class type.
8660 if (RequireNonAbstractType(Var->getLocation(), Type,
8661 diag::err_abstract_type_in_decl,
8662 AbstractVariableType)) {
8663 Var->setInvalidDecl();
8664 return;
8665 }
8666
Douglas Gregor9574af62011-05-21 17:52:48 +00008667 // Check for jumps past the implicit initializer. C++0x
8668 // clarifies that this applies to a "variable with automatic
8669 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008670 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008671 // A program that jumps from a point where a variable with automatic
8672 // storage duration is not in scope to a point where it is in scope is
8673 // ill-formed unless the variable has scalar type, class type with a
8674 // trivial default constructor and a trivial destructor, a cv-qualified
8675 // version of one of these types, or an array of one of the preceding
8676 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008677 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008678 if (const RecordType *Record
8679 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008680 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008681 // Mark the function for further checking even if the looser rules of
8682 // C++11 do not require such checks, so that we can diagnose
8683 // incompatibilities with C++98.
8684 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008685 getCurFunction()->setHasBranchProtectedScope();
8686 }
Douglas Gregore6565622010-02-09 07:26:29 +00008687 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008688
8689 // C++03 [dcl.init]p9:
8690 // If no initializer is specified for an object, and the
8691 // object is of (possibly cv-qualified) non-POD class type (or
8692 // array thereof), the object shall be default-initialized; if
8693 // the object is of const-qualified type, the underlying class
8694 // type shall have a user-declared default
8695 // constructor. Otherwise, if no initializer is specified for
8696 // a non- static object, the object and its subobjects, if
8697 // any, have an indeterminate initial value); if the object
8698 // or any of its subobjects are of const-qualified type, the
8699 // program is ill-formed.
8700 // C++0x [dcl.init]p11:
8701 // If no initializer is specified for an object, the object is
8702 // default-initialized; [...].
8703 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8704 InitializationKind Kind
8705 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008706
8707 InitializationSequence InitSeq(*this, Entity, Kind, None);
8708 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008709 if (Init.isInvalid())
8710 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008711 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008712 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008713 // This is important for template substitution.
8714 Var->setInitStyle(VarDecl::CallInit);
8715 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008716
John McCall8b7fd8f12011-01-19 11:48:09 +00008717 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008718 }
8719}
8720
Richard Smith02e85f32011-04-14 22:09:26 +00008721void Sema::ActOnCXXForRangeDecl(Decl *D) {
8722 VarDecl *VD = dyn_cast<VarDecl>(D);
8723 if (!VD) {
8724 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8725 D->setInvalidDecl();
8726 return;
8727 }
8728
8729 VD->setCXXForRangeDecl(true);
8730
8731 // for-range-declaration cannot be given a storage class specifier.
8732 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008733 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008734 case SC_None:
8735 break;
8736 case SC_Extern:
8737 Error = 0;
8738 break;
8739 case SC_Static:
8740 Error = 1;
8741 break;
8742 case SC_PrivateExtern:
8743 Error = 2;
8744 break;
8745 case SC_Auto:
8746 Error = 3;
8747 break;
8748 case SC_Register:
8749 Error = 4;
8750 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008751 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008752 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008753 }
Richard Smith2316cd82011-09-29 19:11:37 +00008754 if (VD->isConstexpr())
8755 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008756 if (Error != -1) {
8757 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8758 << VD->getDeclName() << Error;
8759 D->setInvalidDecl();
8760 }
8761}
8762
John McCall8b7fd8f12011-01-19 11:48:09 +00008763void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8764 if (var->isInvalidDecl()) return;
8765
John McCall31168b02011-06-15 23:02:42 +00008766 // In ARC, don't allow jumps past the implicit initialization of a
8767 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008768 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008769 var->hasLocalStorage()) {
8770 switch (var->getType().getObjCLifetime()) {
8771 case Qualifiers::OCL_None:
8772 case Qualifiers::OCL_ExplicitNone:
8773 case Qualifiers::OCL_Autoreleasing:
8774 break;
8775
8776 case Qualifiers::OCL_Weak:
8777 case Qualifiers::OCL_Strong:
8778 getCurFunction()->setHasBranchProtectedScope();
8779 break;
8780 }
8781 }
8782
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008783 if (var->isThisDeclarationADefinition() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008784 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimek5704e4e2012-12-12 13:26:54 +00008785 getDiagnostics().getDiagnosticLevel(
8786 diag::warn_missing_variable_declarations,
8787 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008788 // Find a previous declaration that's not a definition.
8789 VarDecl *prev = var->getPreviousDecl();
8790 while (prev && prev->isThisDeclarationADefinition())
8791 prev = prev->getPreviousDecl();
8792
8793 if (!prev)
8794 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8795 }
8796
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008797 if (var->getTLSKind() == VarDecl::TLS_Static &&
8798 var->getType().isDestructedType()) {
8799 // GNU C++98 edits for __thread, [basic.start.term]p3:
8800 // The type of an object with thread storage duration shall not
8801 // have a non-trivial destructor.
8802 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8803 if (getLangOpts().CPlusPlus11)
8804 Diag(var->getLocation(), diag::note_use_thread_local);
8805 }
8806
John McCall8b7fd8f12011-01-19 11:48:09 +00008807 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008808 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008809
Richard Smithde63d362012-11-09 23:03:14 +00008810 QualType type = var->getType();
8811 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008812
8813 // __block variables might require us to capture a copy-initializer.
8814 if (var->hasAttr<BlocksAttr>()) {
8815 // It's currently invalid to ever have a __block variable with an
8816 // array type; should we diagnose that here?
8817
8818 // Regardless, we don't want to ignore array nesting when
8819 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00008820 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00008821 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00008822 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00008823 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00008824 ExprResult result
8825 = PerformMoveOrCopyInitialization(
8826 InitializedEntity::InitializeBlock(poi, type, false),
8827 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00008828 if (!result.isInvalid()) {
8829 result = MaybeCreateExprWithCleanups(result);
8830 Expr *init = result.takeAs<Expr>();
8831 Context.setBlockVarCopyInits(var, init);
8832 }
8833 }
8834 }
8835
Richard Smitheda3c842011-11-07 22:16:17 +00008836 Expr *Init = var->getInit();
8837 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00008838 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00008839
Richard Smithbf830092012-10-29 18:26:47 +00008840 if (!var->getDeclContext()->isDependentContext() &&
8841 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008842 if (IsGlobal && !var->isConstexpr() &&
8843 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8844 var->getLocation())
Eli Friedman4c27ac22013-07-16 22:40:53 +00008845 != DiagnosticsEngine::Ignored) {
8846 // Warn about globals which don't have a constant initializer. Don't
8847 // warn about globals with a non-trivial destructor because we already
8848 // warned about them.
8849 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8850 if (!(RD && !RD->hasTrivialDestructor()) &&
8851 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8852 Diag(var->getLocation(), diag::warn_global_constructor)
8853 << Init->getSourceRange();
8854 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00008855
Richard Smithd0b4dd62011-12-19 06:19:21 +00008856 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008857 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00008858 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8859 SourceLocation DiagLoc = var->getLocation();
8860 // If the note doesn't add any useful information other than a source
8861 // location, fold it into the primary diagnostic.
8862 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8863 diag::note_invalid_subexpr_in_const_expr) {
8864 DiagLoc = Notes[0].first;
8865 Notes.clear();
8866 }
8867 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8868 << var << Init->getSourceRange();
8869 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8870 Diag(Notes[I].first, Notes[I].second);
8871 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00008872 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008873 // Check whether the initializer of a const variable of integral or
8874 // enumeration type is an ICE now, since we can't tell whether it was
8875 // initialized by a constant expression if we check later.
8876 var->checkInitIsICE();
8877 }
Richard Smitheda3c842011-11-07 22:16:17 +00008878 }
John McCall8b7fd8f12011-01-19 11:48:09 +00008879
8880 // Require the destructor.
8881 if (const RecordType *recordType = baseType->getAs<RecordType>())
8882 FinalizeVarWithDestructor(var, recordType);
8883}
8884
Richard Smithb2bc2e62011-02-21 20:05:19 +00008885/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8886/// any semantic actions necessary after any initializer has been attached.
8887void
8888Sema::FinalizeDeclaration(Decl *ThisDecl) {
8889 // Note that we are no longer parsing the initializer for this declaration.
8890 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008891
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008892 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00008893 if (!VD)
8894 return;
8895
Rafael Espindola87198cd2013-08-16 23:18:50 +00008896 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8897 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8898 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8899 VD->dropAttr<UsedAttr>();
8900 }
8901 }
8902
Rafael Espindolad53ffa02013-10-22 21:39:03 +00008903 if (!VD->isInvalidDecl() &&
8904 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8905 if (const VarDecl *Def = VD->getDefinition()) {
8906 if (Def->hasAttr<AliasAttr>()) {
8907 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8908 << VD->getDeclName();
8909 Diag(Def->getLocation(), diag::note_previous_definition);
8910 VD->setInvalidDecl();
8911 }
8912 }
8913 }
8914
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008915 const DeclContext *DC = VD->getDeclContext();
8916 // If there's a #pragma GCC visibility in scope, and this isn't a class
8917 // member, set the visibility of this variable.
Rafael Espindola3ae00052013-05-13 00:12:11 +00008918 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008919 AddPushedVisibilityAttribute(VD);
8920
Rafael Espindolad2ecc132013-01-03 04:29:20 +00008921 if (VD->isFileVarDecl())
8922 MarkUnusedFileScopedDecl(VD);
8923
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008924 // Now we have parsed the initializer and can update the table of magic
8925 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00008926 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8927 !VD->getType()->isIntegralOrEnumerationType())
8928 return;
8929
8930 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8931 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8932 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8933 I != E; ++I) {
8934 const Expr *MagicValueExpr = VD->getInit();
8935 if (!MagicValueExpr) {
8936 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008937 }
Rafael Espindola60470f12013-01-03 04:05:19 +00008938 llvm::APSInt MagicValueInt;
8939 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8940 Diag(I->getRange().getBegin(),
8941 diag::err_type_tag_for_datatype_not_ice)
8942 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8943 continue;
8944 }
8945 if (MagicValueInt.getActiveBits() > 64) {
8946 Diag(I->getRange().getBegin(),
8947 diag::err_type_tag_for_datatype_too_large)
8948 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8949 continue;
8950 }
8951 uint64_t MagicValue = MagicValueInt.getZExtValue();
8952 RegisterTypeTagForDatatype(I->getArgumentKind(),
8953 MagicValue,
8954 I->getMatchingCType(),
8955 I->getLayoutCompatible(),
8956 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008957 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00008958}
8959
Rafael Espindolaab417692013-07-09 12:05:01 +00008960Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8961 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008962 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008963
8964 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00008965 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008966
David Majnemer50ce8352013-09-17 23:57:10 +00008967 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00008968 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00008969 if (Decl *D = Group[i]) {
8970 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8971 if (!FirstDeclaratorInGroup)
8972 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00008973 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00008974 }
Richard Smith2abf6762011-02-23 00:37:57 +00008975
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008976 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00008977 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008978 HandleTagNumbering(*this, Tag);
David Majnemer50ce8352013-09-17 23:57:10 +00008979 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8980 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8981 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008982 }
David Blaikie095deba2012-11-14 01:52:05 +00008983
Rafael Espindolaab417692013-07-09 12:05:01 +00008984 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00008985}
8986
8987/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8988/// group, performing any necessary semantic checking.
8989Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00008990Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00008991 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00008992 // C++0x [dcl.spec.auto]p7:
8993 // If the type deduced for the template parameter U is not the same in each
8994 // deduction, the program is ill-formed.
8995 // FIXME: When initializer-list support is added, a distinction is needed
8996 // between the deduced type U and the deduced type which 'auto' stands for.
8997 // auto a = 0, b = { 1, 2, 3 };
8998 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00008999 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009000 QualType Deduced;
9001 CanQualType DeducedCanon;
9002 VarDecl *DeducedDecl = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009003 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009004 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9005 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009006 // Don't reissue diagnostics when instantiating a template.
9007 if (AT && D->isInvalidDecl())
9008 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009009 QualType U = AT ? AT->getDeducedType() : QualType();
9010 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009011 CanQualType UCanon = Context.getCanonicalType(U);
9012 if (Deduced.isNull()) {
9013 Deduced = U;
9014 DeducedCanon = UCanon;
9015 DeducedDecl = D;
9016 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009017 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9018 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009019 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009020 << Deduced << DeducedDecl->getDeclName()
9021 << U << D->getDeclName()
9022 << DeducedDecl->getInit()->getSourceRange()
9023 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009024 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009025 break;
9026 }
9027 }
9028 }
9029 }
9030 }
9031
Rafael Espindolaab417692013-07-09 12:05:01 +00009032 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009033
Rafael Espindolaab417692013-07-09 12:05:01 +00009034 return DeclGroupPtrTy::make(
9035 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009036}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009037
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009038void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009039 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009040}
9041
Rafael Espindolaab417692013-07-09 12:05:01 +00009042void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009043 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009044 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009045 return;
9046
9047 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9048 Group[0]->getLocation())
9049 == DiagnosticsEngine::Ignored)
9050 return;
9051
Rafael Espindolaab417692013-07-09 12:05:01 +00009052 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009053 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009054 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009055 // additional declaration references:
9056 // 'typedef struct S {} S;'
9057 // 'typedef struct S *S;'
9058 // 'struct S *pS;'
9059 // FinalizeDeclaratorGroup adds these as separate declarations.
9060 Decl *MaybeTagDecl = Group[0];
9061 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009062 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009063 }
9064 }
9065
9066 // See if there are any new comments that are not attached to a decl.
9067 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9068 if (!Comments.empty() &&
9069 !Comments.back()->isAttached()) {
9070 // There is at least one comment that not attached to a decl.
9071 // Maybe it should be attached to one of these decls?
9072 //
9073 // Note that this way we pick up not only comments that precede the
9074 // declaration, but also comments that *follow* the declaration -- thanks to
9075 // the lookahead in the lexer: we've consumed the semicolon and looked
9076 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009077 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009078 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009079 }
9080}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009081
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009082/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9083/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009084Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009085 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009086
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009087 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009088
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009089 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009090 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009091 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009092 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009093 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009094 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9095 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009096 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009097 Diag(DS.getStorageClassSpecLoc(),
9098 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009099 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009100 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009101
Richard Smithb4a9e862013-04-12 22:46:28 +00009102 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9103 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9104 << DeclSpec::getSpecifierName(TSCS);
9105 if (DS.isConstexprSpecified())
9106 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009107 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009108
Richard Smithb4a9e862013-04-12 22:46:28 +00009109 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009110
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009111 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009112 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009113
David Blaikiebbafb8a2012-03-11 07:00:24 +00009114 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009115 // Check that there are no default arguments inside the type of this
9116 // parameter.
9117 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009118
9119 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9120 if (D.getCXXScopeSpec().isSet()) {
9121 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9122 << D.getCXXScopeSpec().getRange();
9123 D.getCXXScopeSpec().clear();
9124 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009125 }
9126
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009127 // Ensure we have a valid name
9128 IdentifierInfo *II = 0;
9129 if (D.hasName()) {
9130 II = D.getIdentifier();
9131 if (!II) {
9132 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9133 << GetNameForDeclarator(D).getName().getAsString();
9134 D.setInvalidType(true);
9135 }
9136 }
9137
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009138 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009139 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009140 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9141 ForRedeclaration);
9142 LookupName(R, S);
9143 if (R.isSingleResult()) {
9144 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009145 if (PrevDecl->isTemplateParameter()) {
9146 // Maybe we will complain about the shadowed template parameter.
9147 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9148 // Just pretend that we didn't see the previous declaration.
9149 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00009150 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009151 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009152 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009153
Chris Lattnerd9773512009-01-21 02:38:50 +00009154 // Recover by removing the name
9155 II = 0;
9156 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009157 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009158 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009159 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009160 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009161
John McCallf7b2fb52010-01-22 00:28:27 +00009162 // Temporarily put parameter variables in the translation unit, not
9163 // the enclosing context. This prevents them from accidentally
9164 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009165 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009166 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009167 D.getIdentifierLoc(), II,
9168 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009169 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009170
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009171 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009172 New->setInvalidDecl();
9173
9174 assert(S->isFunctionPrototypeScope());
9175 assert(S->getFunctionPrototypeDepth() >= 1);
9176 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9177 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009178
Douglas Gregor91f84212008-12-11 16:49:14 +00009179 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009180 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009181 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009182 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009183
Douglas Gregor758a8692009-06-17 21:51:59 +00009184 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009185
Douglas Gregor41866812011-09-12 18:37:38 +00009186 if (D.getDeclSpec().isModulePrivateSpecified())
9187 Diag(New->getLocation(), diag::err_module_private_local)
9188 << 1 << New->getDeclName()
9189 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9190 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9191
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009192 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009193 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9194 }
John McCall48871652010-08-21 09:40:31 +00009195 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009196}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009197
John McCalla3ccba02010-06-04 11:21:44 +00009198/// \brief Synthesizes a variable for a parameter arising from a
9199/// typedef.
9200ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9201 SourceLocation Loc,
9202 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009203 /* FIXME: setting StartLoc == Loc.
9204 Would it be worth to modify callers so as to provide proper source
9205 location for the unnamed parameters, embedding the parameter's type? */
9206 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00009207 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009208 SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00009209 Param->setImplicit();
9210 return Param;
9211}
9212
John McCallc5990642010-08-24 09:05:15 +00009213void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9214 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009215 // Don't diagnose unused-parameter errors in template instantiations; we
9216 // will already have done so in the template itself.
9217 if (!ActiveTemplateInstantiations.empty())
9218 return;
9219
9220 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009221 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009222 !(*Param)->hasAttr<UnusedAttr>()) {
9223 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9224 << (*Param)->getDeclName();
9225 }
9226 }
9227}
9228
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009229void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9230 ParmVarDecl * const *ParamEnd,
9231 QualType ReturnTy,
9232 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009233 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009234 return;
9235
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009236 // Warn if the return value is pass-by-value and larger than the specified
9237 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009238 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009239 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009240 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009241 Diag(D->getLocation(), diag::warn_return_value_size)
9242 << D->getDeclName() << Size;
9243 }
9244
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009245 // Warn if any parameter is pass-by-value and larger than the specified
9246 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009247 for (; Param != ParamEnd; ++Param) {
9248 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009249 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009250 continue;
9251 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009252 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009253 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9254 << (*Param)->getDeclName() << Size;
9255 }
9256}
9257
Abramo Bagnaradff19302011-03-08 08:55:46 +00009258ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9259 SourceLocation NameLoc, IdentifierInfo *Name,
9260 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009261 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009262 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009263 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009264 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009265 T->isObjCLifetimeType()) {
9266
9267 Qualifiers::ObjCLifetime lifetime;
9268
9269 // Special cases for arrays:
9270 // - if it's const, use __unsafe_unretained
9271 // - otherwise, it's an error
9272 if (T->isArrayType()) {
9273 if (!T.isConstQualified()) {
9274 DelayedDiagnostics.add(
9275 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009276 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009277 }
9278 lifetime = Qualifiers::OCL_ExplicitNone;
9279 } else {
9280 lifetime = T->getObjCARCImplicitLifetime();
9281 }
9282 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009283 }
9284
Abramo Bagnaradff19302011-03-08 08:55:46 +00009285 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009286 Context.getAdjustedParameterType(T),
9287 TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009288 StorageClass, 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00009289
9290 // Parameters can not be abstract class types.
9291 // For record types, this is done by the AbstractClassUsageDiagnoser once
9292 // the class has been completely parsed.
9293 if (!CurContext->isRecord() &&
9294 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9295 AbstractParamType))
9296 New->setInvalidDecl();
9297
9298 // Parameter declarators cannot be interface types. All ObjC objects are
9299 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009300 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009301 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009302 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009303 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009304 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009305 T = Context.getObjCObjectPointerType(T);
9306 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009307 }
9308
9309 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9310 // duration shall not be qualified by an address-space qualifier."
9311 // Since all parameters have automatic store duration, they can not have
9312 // an address space.
9313 if (T.getAddressSpace() != 0) {
9314 Diag(NameLoc, diag::err_arg_with_address_space);
9315 New->setInvalidDecl();
9316 }
9317
9318 return New;
9319}
9320
Douglas Gregor170512f2009-04-01 23:51:29 +00009321void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9322 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009323 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009324
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009325 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9326 // for a K&R function.
9327 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009328 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9329 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009330 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009331 SmallString<256> Code;
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009332 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00009333 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009334 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00009335 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00009336 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00009337 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009338
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009339 // Implicitly declare the argument as type 'int' for lack of a better
9340 // type.
John McCall084e83d2011-03-24 11:26:52 +00009341 AttributeFactory attrs;
9342 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009343 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009344 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00009345 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00009346 PrevSpec, DiagID);
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009347 // Use the identifier location for the type source range.
9348 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9349 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009350 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9351 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00009352 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009353 }
9354 }
Mike Stump11289f42009-09-09 15:08:12 +00009355 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009356}
9357
Richard Smith79a52e52012-04-17 22:30:01 +00009358Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00009359 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009360 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009361 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009362
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009363 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009364 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009365 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009366}
9367
Anders Carlsson2a45e402012-12-18 01:29:20 +00009368static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9369 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009370 // Don't warn about invalid declarations.
9371 if (FD->isInvalidDecl())
9372 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009373
Anders Carlsson31c7e882009-12-09 03:30:09 +00009374 // Or declarations that aren't global.
9375 if (!FD->isGlobal())
9376 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009377
Anders Carlsson31c7e882009-12-09 03:30:09 +00009378 // Don't warn about C++ member functions.
9379 if (isa<CXXMethodDecl>(FD))
9380 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009381
Anders Carlsson31c7e882009-12-09 03:30:09 +00009382 // Don't warn about 'main'.
9383 if (FD->isMain())
9384 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009385
Anders Carlsson31c7e882009-12-09 03:30:09 +00009386 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009387 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009388 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009389
9390 // Don't warn about function templates.
9391 if (FD->getDescribedFunctionTemplate())
9392 return false;
9393
9394 // Don't warn about function template specializations.
9395 if (FD->isFunctionTemplateSpecialization())
9396 return false;
9397
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009398 // Don't warn for OpenCL kernels.
9399 if (FD->hasAttr<OpenCLKernelAttr>())
9400 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009401
Anders Carlsson31c7e882009-12-09 03:30:09 +00009402 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009403 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9404 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009405 // Ignore any declarations that occur in function or method
9406 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009407 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009408 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009409
Anders Carlsson31c7e882009-12-09 03:30:09 +00009410 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009411 if (FD->getNumParams() == 0)
9412 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009413 break;
9414 }
Richard Smith541b38b2013-09-20 01:15:31 +00009415
Anders Carlsson31c7e882009-12-09 03:30:09 +00009416 return MissingPrototype;
9417}
9418
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009419void
9420Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9421 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009422 // Don't complain if we're in GNU89 mode and the previous definition
9423 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009424 const FunctionDecl *Definition = EffectiveDefinition;
9425 if (!Definition)
9426 if (!FD->isDefined(Definition))
9427 return;
9428
9429 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009430 return;
9431
9432 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9433 Definition->getStorageClass() == SC_Extern)
9434 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009435 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009436 else
9437 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9438
9439 Diag(Definition->getLocation(), diag::note_previous_definition);
9440 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009441}
Faisal Valia17d19f2013-11-07 05:17:06 +00009442
9443
Faisal Valic1a6dc42013-10-23 16:10:50 +00009444static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9445 Sema &S) {
9446 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009447
9448 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009449 LSI->CallOperator = CallOperator;
9450 LSI->Lambda = LambdaClass;
9451 LSI->ReturnType = CallOperator->getResultType();
9452 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9453
9454 if (LCD == LCD_None)
9455 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9456 else if (LCD == LCD_ByCopy)
9457 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9458 else if (LCD == LCD_ByRef)
9459 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9460 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9461
9462 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9463 LSI->Mutable = !CallOperator->isConst();
9464
Faisal Valia17d19f2013-11-07 05:17:06 +00009465 // Add the captures to the LSI so they can be noted as already
9466 // captured within tryCaptureVar.
9467 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9468 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9469 if (C->capturesVariable()) {
9470 VarDecl *VD = C->getCapturedVar();
9471 if (VD->isInitCapture())
9472 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9473 QualType CaptureType = VD->getType();
9474 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9475 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9476 /*RefersToEnclosingLocal*/true, C->getLocation(),
9477 /*EllipsisLoc*/C->isPackExpansion()
9478 ? C->getEllipsisLoc() : SourceLocation(),
9479 CaptureType, /*Expr*/ 0);
9480
9481 } else if (C->capturesThis()) {
9482 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9483 S.getCurrentThisType(), /*Expr*/ 0);
9484 }
9485 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009486}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009487
John McCall48871652010-08-21 09:40:31 +00009488Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009489 // Clear the last template instantiation error context.
9490 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9491
Douglas Gregor17a7c122009-06-24 00:54:41 +00009492 if (!D)
9493 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009494 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009495
John McCall48871652010-08-21 09:40:31 +00009496 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009497 FD = FunTmpl->getTemplatedDecl();
9498 else
John McCall48871652010-08-21 09:40:31 +00009499 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009500 // If we are instantiating a generic lambda call operator, push
9501 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009502 // that's already been calculated (ActOnLambdaExpr) to prime the current
9503 // LambdaScopeInfo.
9504 // When the template operator is being specialized, the LambdaScopeInfo,
9505 // has to be properly restored so that tryCaptureVariable doesn't try
9506 // and capture any new variables. In addition when calculating potential
9507 // captures during transformation of nested lambdas, it is necessary to
9508 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009509 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009510 assert(ActiveTemplateInstantiations.size() &&
9511 "There should be an active template instantiation on the stack "
9512 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009513 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009514 }
9515 else
9516 // Enter a new function scope
9517 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009518
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009519 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009520 if (!FD->isLateTemplateParsed())
9521 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009522
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009523 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009524 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009525 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9526 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009527 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009528 FD->setInvalidDecl();
9529 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009530 }
9531
Eli Friedman9ad72442009-03-04 07:30:59 +00009532 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009533 // (C99 6.9.1p3, C++ [dcl.fct]p6).
9534 QualType ResultType = FD->getResultType();
9535 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009536 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009537 RequireCompleteType(FD->getLocation(), ResultType,
9538 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009539 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009540
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009541 // GNU warning -Wmissing-prototypes:
9542 // Warn if a global function is defined without a previous
9543 // prototype declaration. This warning is issued even if the
9544 // definition itself provides a prototype. The aim is to detect
9545 // global functions that fail to be declared in header files.
Anders Carlsson2a45e402012-12-18 01:29:20 +00009546 const FunctionDecl *PossibleZeroParamPrototype = 0;
9547 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009548 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009549
Anders Carlsson2a45e402012-12-18 01:29:20 +00009550 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009551 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009552 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009553 if (TypeSourceInfo *TI =
9554 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9555 TypeLoc TL = TI->getTypeLoc();
9556 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9557 Diag(PossibleZeroParamPrototype->getLocation(),
9558 diag::note_declaration_not_a_prototype)
9559 << PossibleZeroParamPrototype
9560 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9561 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009562 }
9563 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009564
Douglas Gregor67da0d92009-05-15 17:59:04 +00009565 if (FnBodyScope)
9566 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009567
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009568 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009569 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9570 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009571
9572 // Introduce our parameters into the function scope
9573 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9574 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00009575 Param->setOwningFunction(FD);
9576
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009577 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009578 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009579 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009580
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009581 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009582 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009583 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009584
James Molloy6f8780b2012-02-29 10:24:19 +00009585 // If we had any tags defined in the function prototype,
9586 // introduce them into the function scope.
9587 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009588 for (ArrayRef<NamedDecl *>::iterator
9589 I = FD->getDeclsInPrototypeScope().begin(),
9590 E = FD->getDeclsInPrototypeScope().end();
9591 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009592 NamedDecl *D = *I;
9593
9594 // Some of these decls (like enums) may have been pinned to the translation unit
9595 // for lack of a real context earlier. If so, remove from the translation unit
9596 // and reattach to the current context.
9597 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9598 // Is the decl actually in the context?
9599 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9600 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9601 if (*DI == D) {
9602 Context.getTranslationUnitDecl()->removeDecl(D);
9603 break;
9604 }
9605 }
9606 // Either way, reassign the lexical decl context to our FunctionDecl.
9607 D->setLexicalDeclContext(CurContext);
9608 }
9609
9610 // If the decl has a non-null name, make accessible in the current scope.
9611 if (!D->getName().empty())
9612 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9613
9614 // Similarly, dive into enums and fish their constants out, making them
9615 // accessible in this scope.
9616 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9617 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9618 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie40ed2972012-06-06 20:45:41 +00009619 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009620 }
9621 }
9622 }
9623
Richard Smith79a52e52012-04-17 22:30:01 +00009624 // Ensure that the function's exception specification is instantiated.
9625 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9626 ResolveExceptionSpec(D->getLocation(), FPT);
9627
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009628 // Checking attributes of current function definition
9629 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009630 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9631 if (DA && (!FD->getAttr<DLLExportAttr>())) {
9632 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00009633 // Microsoft accepts dllimport for functions defined within class scope.
9634 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00009635 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009636 Diag(FD->getLocation(),
9637 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9638 << "dllimport";
9639 FD->setInvalidDecl();
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009640 return D;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00009641 }
9642
9643 // Visual C++ appears to not think this is an issue, so only issue
9644 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00009645 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009646 // If a symbol previously declared dllimport is later defined, the
9647 // attribute is ignored in subsequent references, and a warning is
9648 // emitted.
9649 Diag(FD->getLocation(),
9650 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00009651 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009652 }
9653 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009654 // We want to attach documentation to original Decl (which might be
9655 // a function template).
9656 ActOnDocumentableDecl(D);
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009657 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009658}
9659
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009660/// \brief Given the set of return statements within a function body,
9661/// compute the variables that are subject to the named return value
9662/// optimization.
9663///
9664/// Each of the variables that is subject to the named return value
9665/// optimization will be marked as NRVO variables in the AST, and any
9666/// return statement that has a marked NRVO variable as its NRVO candidate can
9667/// use the named return value optimization.
9668///
9669/// This function applies a very simplistic algorithm for NRVO: if every return
9670/// statement in the function has the same NRVO candidate, that candidate is
9671/// the NRVO variable.
9672///
9673/// FIXME: Employ a smarter algorithm that accounts for multiple return
9674/// statements and the lifetimes of the NRVO candidates. We should be able to
9675/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00009676void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009677 ReturnStmt **Returns = Scope->Returns.data();
9678
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009679 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00009680 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009681 if (!Returns[I]->getNRVOCandidate())
9682 return;
9683
9684 if (!NRVOCandidate)
9685 NRVOCandidate = Returns[I]->getNRVOCandidate();
9686 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9687 return;
9688 }
9689
9690 if (NRVOCandidate)
9691 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9692}
9693
Richard Smith1ab34b32012-11-19 21:13:18 +00009694bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith9219d1b2012-11-27 21:31:01 +00009695 if (!Consumer.shouldSkipFunctionBody(D))
9696 return false;
9697
Richard Smith1ab34b32012-11-19 21:13:18 +00009698 if (isa<ObjCMethodDecl>(D))
9699 return true;
9700
9701 FunctionDecl *FD = 0;
9702 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9703 FD = FTD->getTemplatedDecl();
9704 else
9705 FD = cast<FunctionDecl>(D);
9706
9707 // We cannot skip the body of a function (or function template) which is
9708 // constexpr, since we may need to evaluate its body in order to parse the
9709 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009710 // We cannot skip the body of a function with an undeduced return type,
9711 // because any callers of that function need to know the type.
9712 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
Richard Smith1ab34b32012-11-19 21:13:18 +00009713}
9714
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009715Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009716 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009717 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009718 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009719 MD->setHasSkippedBody();
9720 return ActOnFinishFunctionBody(Decl, 0);
9721}
9722
John McCallfaf5fb42010-08-26 23:41:50 +00009723Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009724 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009725}
9726
John McCallb268a282010-08-23 23:25:46 +00009727Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9728 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009729 FunctionDecl *FD = 0;
9730 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9731 if (FunTmpl)
9732 FD = FunTmpl->getTemplatedDecl();
9733 else
9734 FD = dyn_cast_or_null<FunctionDecl>(dcl);
9735
Ted Kremenek0b405322010-03-23 00:13:23 +00009736 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00009737 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00009738
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009739 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009740 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009741
Richard Smith7500ab22013-05-10 04:31:10 +00009742 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9743 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9744 // If the function has a deduced result type but contains no 'return'
9745 // statements, the result type as written must be exactly 'auto', and
9746 // the deduced result type is 'void'.
9747 if (!FD->getResultType()->getAs<AutoType>()) {
9748 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9749 << FD->getResultType();
9750 FD->setInvalidDecl();
9751 } else {
9752 // Substitute 'void' for the 'auto' in the type.
9753 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9754 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9755 Context.adjustDeducedFunctionResultType(
9756 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009757 }
9758 }
9759
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009760 // The only way to be included in UndefinedButUsed is if there is an
9761 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009762 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009763 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009764 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009765 UndefinedButUsed.erase(FD);
9766 else if (FD->isInlined() &&
9767 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9768 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9769 UndefinedButUsed.erase(FD);
9770 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009771
John McCall5ed3caf2012-02-14 19:50:52 +00009772 // If the function implicitly returns zero (like 'main') or is naked,
9773 // don't complain about missing return statements.
9774 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009775 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00009776
Francois Pichet3abc9b82011-05-11 02:14:46 +00009777 // MSVC permits the use of pure specifier (=0) on function definition,
9778 // defined at class scope, warn about this non standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +00009779 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +00009780 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9781
Douglas Gregor88d292c2010-05-13 16:44:06 +00009782 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009783 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009784 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9785 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009786
9787 // If this is a constructor, we need a vtable.
9788 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9789 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009790
Jordan Rosed39e5f12012-07-02 21:19:23 +00009791 // Try to apply the named return value optimization. We have to check
9792 // if we can do this here because lambdas keep return statements around
9793 // to deduce an implicit return type.
9794 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9795 !FD->isDependentContext())
9796 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00009797 }
9798
Douglas Gregor21f46922012-02-08 20:17:14 +00009799 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9800 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00009801 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00009802 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00009803 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009804 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009805 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009806 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9807 MD->getResultType(), MD);
Douglas Gregore3f3ea02011-09-06 20:33:37 +00009808
9809 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00009810 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009811 }
Jordan Rose2afd6612012-10-19 16:05:26 +00009812 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00009813 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9814 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00009815 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00009816 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009817 } else {
John McCall48871652010-08-21 09:40:31 +00009818 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009819 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009820
Jordan Rose2afd6612012-10-19 16:05:26 +00009821 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009822 "This should only be set for ObjC methods, which should have been "
9823 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00009824
Chris Lattnere2473062007-05-28 06:28:18 +00009825 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00009826 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009827 // C++ constructors that have function-try-blocks can't have return
9828 // statements in the handlers of that block. (C++ [except.handle]p14)
9829 // Verify this.
9830 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9831 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9832
Richard Smithdef8bdb2011-08-12 18:44:32 +00009833 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00009834 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00009835 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009836 !hasAnyUnrecoverableErrorsInThisFunction() &&
9837 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00009838 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00009839
John McCalldeb646e2010-08-04 01:04:25 +00009840 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9841 if (!Destructor->getParent()->isDependentType())
9842 CheckDestructor(Destructor);
9843
John McCalla6309952010-03-16 21:39:52 +00009844 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9845 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00009846 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00009847
9848 // If any errors have occurred, clear out any temporaries that may have
9849 // been leftover. This ensures that these temporaries won't be picked up for
9850 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00009851 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00009852 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00009853 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00009854 }
9855 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9856 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00009857 // Since the body is valid, issue any analysis-based warnings that are
9858 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00009859 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00009860 }
9861
Richard Smith3607ffe2012-02-13 03:54:03 +00009862 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9863 (!CheckConstexprFunctionDecl(FD) ||
9864 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00009865 FD->setInvalidDecl();
9866
John McCall28fc7092011-11-10 05:35:25 +00009867 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00009868 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00009869 assert(MaybeODRUseExprs.empty() &&
9870 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00009871 }
9872
John McCalle99d5f32010-03-25 22:08:03 +00009873 if (!IsInstantiation)
9874 PopDeclContext();
9875
Eli Friedman71c80552012-01-05 03:35:19 +00009876 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +00009877 // If any errors have occurred, clear out any temporaries that may have
9878 // been leftover. This ensures that these temporaries won't be picked up for
9879 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00009880 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00009881 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00009882 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00009883
John McCall48871652010-08-21 09:40:31 +00009884 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00009885}
9886
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009887
9888/// When we finish delayed parsing of an attribute, we must attach it to the
9889/// relevant Decl.
9890void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9891 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00009892 // Always attach attributes to the underlying decl.
9893 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9894 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00009895 ProcessDeclAttributeList(S, D, Attrs.getList());
9896
9897 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9898 if (Method->isStatic())
9899 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009900}
9901
9902
Chris Lattnerac18be92006-11-20 06:49:47 +00009903/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9904/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00009905NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00009906 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009907 // Before we produce a declaration for an implicitly defined
9908 // function, see whether there was a locally-scoped declaration of
9909 // this name as a function or variable. If so, use that
9910 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +00009911 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9912 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9913 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9914 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009915 }
9916
Chris Lattner00e26072008-05-05 21:18:06 +00009917 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00009918 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00009919 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00009920 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009921 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00009922 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00009923 else
Hans Wennborg70a13242011-12-08 15:56:07 +00009924 diag_id = diag::warn_implicit_function_decl;
9925 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00009926
Hans Wennborg70a13242011-12-08 15:56:07 +00009927 // Because typo correction is expensive, only do it if the implicit
9928 // function declaration is going to be treated as an error.
9929 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9930 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00009931 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00009932 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smithf9b15102013-08-17 00:46:16 +00009933 LookupOrdinaryName, S, 0, Validator)))
9934 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9935 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +00009936 }
9937
Chris Lattnerac18be92006-11-20 06:49:47 +00009938 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00009939 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00009940 AttributeFactory attrFactory;
9941 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00009942 unsigned DiagID;
9943 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009944 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00009945 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009946 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +00009947 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009948 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9949 /*IsAmbiguous=*/false,
9950 /*RParenLoc=*/NoLoc,
9951 /*ArgInfo=*/0,
9952 /*NumArgs=*/0,
9953 /*EllipsisLoc=*/NoLoc,
9954 /*RParenLoc=*/NoLoc,
9955 /*TypeQuals=*/0,
9956 /*RefQualifierIsLvalueRef=*/true,
9957 /*RefQualifierLoc=*/NoLoc,
9958 /*ConstQualifierLoc=*/NoLoc,
9959 /*VolatileQualifierLoc=*/NoLoc,
9960 /*MutableLoc=*/NoLoc,
9961 EST_None,
9962 /*ESpecLoc=*/NoLoc,
9963 /*Exceptions=*/0,
9964 /*ExceptionRanges=*/0,
9965 /*NumExceptions=*/0,
9966 /*NoexceptExpr=*/0,
9967 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00009968 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009969 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00009970 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009971
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00009972 // Insert this function into translation-unit scope.
9973
9974 DeclContext *PrevDC = CurContext;
9975 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009976
Jordan Rosed03d99d2013-03-05 01:27:54 +00009977 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00009978 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00009979
9980 CurContext = PrevDC;
9981
Douglas Gregore711f702009-02-14 18:57:46 +00009982 AddKnownFunctionAttributes(FD);
9983
Steve Naroff3913ea42008-04-04 14:32:09 +00009984 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00009985}
9986
Douglas Gregore711f702009-02-14 18:57:46 +00009987/// \brief Adds any function attributes that we know a priori based on
9988/// the declaration of this function.
9989///
9990/// These attributes can apply both to implicitly-declared builtins
9991/// (like __builtin___printf_chk) or to library-declared functions
9992/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +00009993///
9994/// We need to check for duplicate attributes both here and where user-written
9995/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +00009996void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9997 if (FD->isInvalidDecl())
9998 return;
9999
10000 // If this is a built-in function, map its builtin attributes to
10001 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010002 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010003 // Handle printf-formatting attributes.
10004 unsigned FormatIdx;
10005 bool HasVAListArg;
10006 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010007 if (!FD->getAttr<FormatAttr>()) {
10008 const char *fmt = "printf";
10009 unsigned int NumParams = FD->getNumParams();
10010 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10011 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10012 fmt = "NSString";
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010013 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010014 &Context.Idents.get(fmt),
10015 FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +000010016 HasVAListArg ? 0 : FormatIdx+2));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010017 }
Douglas Gregore711f702009-02-14 18:57:46 +000010018 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010019 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10020 HasVAListArg)) {
10021 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010022 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010023 &Context.Idents.get("scanf"),
10024 FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +000010025 HasVAListArg ? 0 : FormatIdx+2));
10026 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010027
10028 // Mark const if we don't care about errno and that is the only
10029 // thing preventing the function from being const. This allows
10030 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010031 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010032 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000010033 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010034 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010035 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010036
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010037 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10038 !FD->getAttr<ReturnsTwiceAttr>())
10039 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +000010040 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010041 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +000010042 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010043 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +000010044 }
10045
10046 IdentifierInfo *Name = FD->getIdentifier();
10047 if (!Name)
10048 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010049 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010050 FD->getDeclContext()->isTranslationUnit()) ||
10051 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010052 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010053 LinkageSpecDecl::lang_c)) {
10054 // Okay: this could be a libc/libm/Objective-C function we know
10055 // about.
10056 } else
10057 return;
10058
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010059 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010060 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010061 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000010062 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +000010063 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010064 &Context.Idents.get("printf"), 2,
Eli Friedmanf4799842009-06-10 04:01:38 +000010065 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010066 }
Jordan Rose742c6072012-08-08 21:17:31 +000010067
10068 if (Name->isStr("__CFStringMakeConstantString")) {
10069 // We already have a __builtin___CFStringMakeConstantString,
10070 // but builds that use -fno-constant-cfstrings don't go through that.
10071 if (!FD->getAttr<FormatArgAttr>())
10072 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10073 }
Douglas Gregore711f702009-02-14 18:57:46 +000010074}
Chris Lattner302b4be2006-11-19 02:31:38 +000010075
John McCall703a3f82009-10-24 08:00:42 +000010076TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010077 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010078 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010079 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010080
John McCallbcd03502009-12-07 02:54:59 +000010081 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010082 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010083 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010084 }
10085
Chris Lattner18b19622007-01-22 07:39:13 +000010086 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010087 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010088 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010089 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010090 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010091 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010092
John McCall04fcd0d2011-02-01 08:20:08 +000010093 // Bail out immediately if we have an invalid declaration.
10094 if (D.isInvalidType()) {
10095 NewTD->setInvalidDecl();
10096 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010097 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010098
Douglas Gregor41866812011-09-12 18:37:38 +000010099 if (D.getDeclSpec().isModulePrivateSpecified()) {
10100 if (CurContext->isFunctionOrMethod())
10101 Diag(NewTD->getLocation(), diag::err_module_private_local)
10102 << 2 << NewTD->getDeclName()
10103 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10104 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10105 else
10106 NewTD->setModulePrivate();
10107 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010108
John McCall04fcd0d2011-02-01 08:20:08 +000010109 // C++ [dcl.typedef]p8:
10110 // If the typedef declaration defines an unnamed class (or
10111 // enum), the first typedef-name declared by the declaration
10112 // to be that class type (or enum type) is used to denote the
10113 // class type (or enum type) for linkage purposes only.
10114 // We need to check whether the type was declared in the declaration.
10115 switch (D.getDeclSpec().getTypeSpecType()) {
10116 case TST_enum:
10117 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010118 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010119 case TST_union:
10120 case TST_class: {
10121 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10122
10123 // Do nothing if the tag is not anonymous or already has an
10124 // associated typedef (from an earlier typedef in this decl group).
10125 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010126 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010127
10128 // A well-formed anonymous tag must always be a TUK_Definition.
10129 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10130
10131 // The type must match the tag exactly; no qualifiers allowed.
10132 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10133 break;
10134
10135 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010136 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010137 break;
10138 }
10139
10140 default:
10141 break;
10142 }
10143
Steve Narofff93b6722007-08-28 20:14:24 +000010144 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010145}
10146
Douglas Gregord9034f02009-05-14 16:41:31 +000010147
Richard Smith4b38ded2012-03-14 23:13:10 +000010148/// \brief Check that this is a valid underlying type for an enum declaration.
10149bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10150 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10151 QualType T = TI->getType();
10152
Eli Friedman52f32b92012-12-18 02:37:32 +000010153 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010154 return false;
10155
Eli Friedman52f32b92012-12-18 02:37:32 +000010156 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10157 if (BT->isInteger())
10158 return false;
10159
Richard Smith4b38ded2012-03-14 23:13:10 +000010160 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10161 return true;
10162}
10163
10164/// Check whether this is a valid redeclaration of a previous enumeration.
10165/// \return true if the redeclaration was invalid.
10166bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10167 QualType EnumUnderlyingTy,
10168 const EnumDecl *Prev) {
10169 bool IsFixed = !EnumUnderlyingTy.isNull();
10170
10171 if (IsScoped != Prev->isScoped()) {
10172 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10173 << Prev->isScoped();
10174 Diag(Prev->getLocation(), diag::note_previous_use);
10175 return true;
10176 }
10177
10178 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010179 if (!EnumUnderlyingTy->isDependentType() &&
10180 !Prev->getIntegerType()->isDependentType() &&
10181 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010182 Prev->getIntegerType())) {
10183 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10184 << EnumUnderlyingTy << Prev->getIntegerType();
10185 Diag(Prev->getLocation(), diag::note_previous_use);
10186 return true;
10187 }
10188 } else if (IsFixed != Prev->isFixed()) {
10189 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10190 << Prev->isFixed();
10191 Diag(Prev->getLocation(), diag::note_previous_use);
10192 return true;
10193 }
10194
10195 return false;
10196}
10197
Joao Matosdc86f942012-08-31 18:45:21 +000010198/// \brief Get diagnostic %select index for tag kind for
10199/// redeclaration diagnostic message.
10200/// WARNING: Indexes apply to particular diagnostics only!
10201///
10202/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010203static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010204 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010205 case TTK_Struct: return 0;
10206 case TTK_Interface: return 1;
10207 case TTK_Class: return 2;
10208 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010209 }
Joao Matosdc86f942012-08-31 18:45:21 +000010210}
10211
10212/// \brief Determine if tag kind is a class-key compatible with
10213/// class for redeclaration (class, struct, or __interface).
10214///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010215/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010216static bool isClassCompatTagKind(TagTypeKind Tag)
10217{
10218 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10219}
10220
Douglas Gregord9034f02009-05-14 16:41:31 +000010221/// \brief Determine whether a tag with a given kind is acceptable
10222/// as a redeclaration of the given tag declaration.
10223///
10224/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010225bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010226 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010227 SourceLocation NewTagLoc,
10228 const IdentifierInfo &Name) {
10229 // C++ [dcl.type.elab]p3:
10230 // The class-key or enum keyword present in the
10231 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010232 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010233 // refers. This rule also applies to the form of
10234 // elaborated-type-specifier that declares a class-name or
10235 // friend class since it can be construed as referring to the
10236 // definition of the class. Thus, in any
10237 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010238 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010239 // used to refer to a union (clause 9), and either the class or
10240 // struct class-key shall be used to refer to a class (clause 9)
10241 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010242 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010243 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010244 if (OldTag == NewTag)
10245 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010246
Joao Matosdc86f942012-08-31 18:45:21 +000010247 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010248 // Warn about the struct/class tag mismatch.
10249 bool isTemplate = false;
10250 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10251 isTemplate = Record->getDescribedClassTemplate();
10252
Richard Trieucaa33d32011-06-10 03:11:26 +000010253 if (!ActiveTemplateInstantiations.empty()) {
10254 // In a template instantiation, do not offer fix-its for tag mismatches
10255 // since they usually mess up the template instead of fixing the problem.
10256 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010257 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10258 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010259 return true;
10260 }
10261
10262 if (isDefinition) {
10263 // On definitions, check previous tags and issue a fix-it for each
10264 // one that doesn't match the current tag.
10265 if (Previous->getDefinition()) {
10266 // Don't suggest fix-its for redefinitions.
10267 return true;
10268 }
10269
10270 bool previousMismatch = false;
10271 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10272 E(Previous->redecls_end()); I != E; ++I) {
10273 if (I->getTagKind() != NewTag) {
10274 if (!previousMismatch) {
10275 previousMismatch = true;
10276 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010277 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10278 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010279 }
10280 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010281 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010282 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010283 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010284 }
10285 }
10286 return true;
10287 }
10288
10289 // Check for a previous definition. If current tag and definition
10290 // are same type, do nothing. If no definition, but disagree with
10291 // with previous tag type, give a warning, but no fix-it.
10292 const TagDecl *Redecl = Previous->getDefinition() ?
10293 Previous->getDefinition() : Previous;
10294 if (Redecl->getTagKind() == NewTag) {
10295 return true;
10296 }
10297
Douglas Gregord9034f02009-05-14 16:41:31 +000010298 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010299 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10300 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010301 Diag(Redecl->getLocation(), diag::note_previous_use);
10302
10303 // If there is a previous defintion, suggest a fix-it.
10304 if (Previous->getDefinition()) {
10305 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010306 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010307 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010308 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010309 }
10310
Douglas Gregord9034f02009-05-14 16:41:31 +000010311 return true;
10312 }
10313 return false;
10314}
10315
Steve Naroff30d242c2007-09-15 18:49:24 +000010316/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010317/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010318/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010319/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +000010320Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010321 SourceLocation KWLoc, CXXScopeSpec &SS,
10322 IdentifierInfo *Name, SourceLocation NameLoc,
10323 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010324 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010325 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010326 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010327 SourceLocation ScopedEnumKWLoc,
10328 bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010329 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010330 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010331 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010332 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010333 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010334 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010335
Douglas Gregord6ab8742009-05-28 23:31:59 +000010336 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010337 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010338 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010339
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010340 // FIXME: Check explicit specializations more carefully.
10341 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010342 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010343
10344 // We only need to do this matching if we have template parameters
10345 // or a scope specifier, which also conveniently avoids this work
10346 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010347 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010348 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010349 if (TemplateParameterList *TemplateParams =
10350 MatchTemplateParametersToScopeSpecifier(
10351 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10352 isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010353 if (Kind == TTK_Enum) {
10354 Diag(KWLoc, diag::err_enum_template);
10355 return 0;
10356 }
10357
Douglas Gregor3dad8422009-09-26 06:47:28 +000010358 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010359 // This is a declaration or definition of a class template (which may
10360 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010361
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010362 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010363 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010364
Douglas Gregore93e46c2009-07-22 23:48:44 +000010365 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010366 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010367 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010368 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010369 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010370 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010371 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010372 return Result.get();
10373 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010374 // The "template<>" header is extraneous.
10375 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010376 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010377 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010378 }
Mike Stump11289f42009-09-09 15:08:12 +000010379 }
10380 }
10381
Douglas Gregor0bf31402010-10-08 23:50:27 +000010382 // Figure out the underlying type if this a enum declaration. We need to do
10383 // this early, because it's needed to detect if this is an incompatible
10384 // redeclaration.
10385 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10386
10387 if (Kind == TTK_Enum) {
10388 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10389 // No underlying type explicitly specified, or we failed to parse the
10390 // type, default to int.
10391 EnumUnderlying = Context.IntTy.getTypePtr();
10392 else if (UnderlyingType.get()) {
10393 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10394 // integral type; any cv-qualification is ignored.
10395 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010396 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010397 EnumUnderlying = TI;
10398
Richard Smith4b38ded2012-03-14 23:13:10 +000010399 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010400 // Recover by falling back to int.
10401 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010402
Richard Smith4b38ded2012-03-14 23:13:10 +000010403 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010404 UPPC_FixedUnderlyingType))
10405 EnumUnderlying = Context.IntTy.getTypePtr();
10406
David Blaikiebbafb8a2012-03-11 07:00:24 +000010407 } else if (getLangOpts().MicrosoftMode)
Francois Picheta3108062010-10-18 15:01:13 +000010408 // Microsoft enums are always of int type.
10409 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010410 }
10411
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010412 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010413 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010414 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010415
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010416 RedeclarationKind Redecl = ForRedeclaration;
10417 if (TUK == TUK_Friend || TUK == TUK_Reference)
10418 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010419
10420 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010421 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010422 if (Name && SS.isNotEmpty()) {
10423 // We have a nested-name tag ('struct foo::bar').
10424
10425 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010426 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010427 Name = 0;
10428 goto CreateNewDecl;
10429 }
10430
John McCall7f41d982009-09-11 04:59:25 +000010431 // If this is a friend or a reference to a class in a dependent
10432 // context, don't try to make a decl for it.
10433 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10434 DC = computeDeclContext(SS, false);
10435 if (!DC) {
10436 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010437 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010438 }
John McCall0b66eb32010-05-01 00:40:08 +000010439 } else {
10440 DC = computeDeclContext(SS, true);
10441 if (!DC) {
10442 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10443 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010444 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010445 }
John McCall7f41d982009-09-11 04:59:25 +000010446 }
10447
John McCall0b66eb32010-05-01 00:40:08 +000010448 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010449 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010450
Douglas Gregor8761da52009-02-03 00:34:39 +000010451 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010452 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010453 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010454
John McCall1f82f242009-11-18 22:49:29 +000010455 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010456 return 0;
John McCall6538c932009-10-10 05:48:19 +000010457
John McCall1f82f242009-11-18 22:49:29 +000010458 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010459 // Name lookup did not find anything. However, if the
10460 // nested-name-specifier refers to the current instantiation,
10461 // and that current instantiation has any dependent base
10462 // classes, we might find something at instantiation time: treat
10463 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010464 // But this only makes any sense for reference-like lookups.
10465 if (Previous.wasNotFoundInCurrentInstantiation() &&
10466 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010467 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010468 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010469 }
10470
10471 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010472 Diag(NameLoc, diag::err_not_tag_in_scope)
10473 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010474 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010475 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010476 goto CreateNewDecl;
10477 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010478 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010479 // If this is a named struct, check to see if there was a previous forward
10480 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010481 // FIXME: We're looking into outer scopes here, even when we
10482 // shouldn't be. Doing so can result in ambiguities that we
10483 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010484 LookupName(Previous, S);
10485
John McCall3c581bf2013-03-20 01:53:00 +000010486 // When declaring or defining a tag, ignore ambiguities introduced
10487 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010488 if (Previous.isAmbiguous() &&
10489 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010490 LookupResult::Filter F = Previous.makeFilter();
10491 while (F.hasNext()) {
10492 NamedDecl *ND = F.next();
10493 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10494 F.erase();
10495 }
10496 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010497 }
John McCall3c581bf2013-03-20 01:53:00 +000010498
10499 // C++11 [namespace.memdef]p3:
10500 // If the name in a friend declaration is neither qualified nor
10501 // a template-id and the declaration is a function or an
10502 // elaborated-type-specifier, the lookup to determine whether
10503 // the entity has been previously declared shall not consider
10504 // any scopes outside the innermost enclosing namespace.
10505 //
10506 // Does it matter that this should be by scope instead of by
10507 // semantic context?
10508 if (!Previous.empty() && TUK == TUK_Friend) {
10509 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10510 LookupResult::Filter F = Previous.makeFilter();
10511 while (F.hasNext()) {
10512 NamedDecl *ND = F.next();
10513 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010514 if (DC->isFileContext() &&
10515 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010516 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010517 FriendSawTagOutsideEnclosingNamespace = true;
10518 }
John McCall3c581bf2013-03-20 01:53:00 +000010519 }
10520 F.done();
10521 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010522
John McCall1f82f242009-11-18 22:49:29 +000010523 // Note: there used to be some attempt at recovery here.
10524 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010525 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010526
David Blaikiebbafb8a2012-03-11 07:00:24 +000010527 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010528 // FIXME: This makes sure that we ignore the contexts associated
10529 // with C structs, unions, and enums when looking for a matching
10530 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010531 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010532 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10533 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010534 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010535 } else if (S->isFunctionPrototypeScope()) {
10536 // If this is an enum declaration in function prototype scope, set its
10537 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010538 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010539 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010540 }
10541
John McCall1f82f242009-11-18 22:49:29 +000010542 if (Previous.isSingleResult() &&
10543 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010544 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010545 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010546 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010547 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010548 }
10549
David Blaikiebbafb8a2012-03-11 07:00:24 +000010550 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010551 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010552 // This is a declaration of or a reference to "std::bad_alloc".
10553 isStdBadAlloc = true;
10554
John McCall1f82f242009-11-18 22:49:29 +000010555 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010556 // std::bad_alloc has been implicitly declared (but made invisible to
10557 // name lookup). Fill in this implicit declaration as the previous
10558 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010559 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010560 }
10561 }
John McCall1f82f242009-11-18 22:49:29 +000010562
John McCalle9eaf8e2010-03-25 21:28:06 +000010563 // If we didn't find a previous declaration, and this is a reference
10564 // (or friend reference), move to the correct scope. In C++, we
10565 // also need to do a redeclaration lookup there, just in case
10566 // there's a shadow friend decl.
10567 if (Name && Previous.empty() &&
10568 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10569 if (Invalid) goto CreateNewDecl;
10570 assert(SS.isEmpty());
10571
10572 if (TUK == TUK_Reference) {
10573 // C++ [basic.scope.pdecl]p5:
10574 // -- for an elaborated-type-specifier of the form
10575 //
10576 // class-key identifier
10577 //
10578 // if the elaborated-type-specifier is used in the
10579 // decl-specifier-seq or parameter-declaration-clause of a
10580 // function defined in namespace scope, the identifier is
10581 // declared as a class-name in the namespace that contains
10582 // the declaration; otherwise, except as a friend
10583 // declaration, the identifier is declared in the smallest
10584 // non-class, non-function-prototype scope that contains the
10585 // declaration.
10586 //
10587 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10588 // C structs and unions.
10589 //
10590 // It is an error in C++ to declare (rather than define) an enum
10591 // type, including via an elaborated type specifier. We'll
10592 // diagnose that later; for now, declare the enum in the same
10593 // scope as we would have picked for any other tag type.
10594 //
10595 // GNU C also supports this behavior as part of its incomplete
10596 // enum types extension, while GNU C++ does not.
10597 //
10598 // Find the context where we'll be declaring the tag.
10599 // FIXME: We would like to maintain the current DeclContext as the
10600 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010601 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010602 SearchDC = SearchDC->getParent();
10603
10604 // Find the scope where we'll be declaring the tag.
10605 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010606 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010607 S->isFunctionPrototypeScope()) ||
10608 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010609 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010610 S = S->getParent();
10611 } else {
10612 assert(TUK == TUK_Friend);
10613 // C++ [namespace.memdef]p3:
10614 // If a friend declaration in a non-local class first declares a
10615 // class or function, the friend class or function is a member of
10616 // the innermost enclosing namespace.
10617 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010618 }
10619
John McCalle87beb22010-04-23 18:46:30 +000010620 // In C++, we need to do a redeclaration lookup to properly
10621 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010622 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010623 Previous.setRedeclarationKind(ForRedeclaration);
10624 LookupQualifiedName(Previous, SearchDC);
10625 }
10626 }
10627
John McCall1f82f242009-11-18 22:49:29 +000010628 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +000010629 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +000010630
10631 // It's okay to have a tag decl in the same scope as a typedef
10632 // which hides a tag decl in the same scope. Finding this
10633 // insanity with a redeclaration lookup can only actually happen
10634 // in C++.
10635 //
10636 // This is also okay for elaborated-type-specifiers, which is
10637 // technically forbidden by the current standard but which is
10638 // okay according to the likely resolution of an open issue;
10639 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010640 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010641 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010642 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10643 TagDecl *Tag = TT->getDecl();
10644 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010645 Tag->getDeclContext()->getRedeclContext()
10646 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010647 PrevDecl = Tag;
10648 Previous.clear();
10649 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010650 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010651 }
10652 }
10653 }
10654 }
10655
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010656 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010657 // If this is a use of a previous tag, or if the tag is already declared
10658 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010659 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010660 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +000010661 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010662 // Make sure that this wasn't declared as an enum and now used as a
10663 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010664 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10665 TUK == TUK_Definition, KWLoc,
10666 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010667 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010668 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10669 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010670 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010671 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010672 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010673 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10674 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010675 else
10676 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010677 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010678
Mike Stump11289f42009-09-09 15:08:12 +000010679 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010680 Kind = PrevTagDecl->getTagKind();
10681 else {
10682 // Recover by making this an anonymous redefinition.
10683 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010684 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010685 Invalid = true;
10686 }
10687 }
10688
Douglas Gregor0bf31402010-10-08 23:50:27 +000010689 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10690 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10691
Richard Smith0f8ee222012-01-10 01:33:14 +000010692 // If this is an elaborated-type-specifier for a scoped enumeration,
10693 // the 'class' keyword is not necessary and not permitted.
10694 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10695 if (ScopedEnum)
10696 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10697 << PrevEnum->isScoped()
10698 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10699 return PrevTagDecl;
10700 }
10701
Richard Smith4b38ded2012-03-14 23:13:10 +000010702 QualType EnumUnderlyingTy;
10703 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10704 EnumUnderlyingTy = TI->getType();
10705 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10706 EnumUnderlyingTy = QualType(T, 0);
10707
Douglas Gregor0bf31402010-10-08 23:50:27 +000010708 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010709 // returning the previous declaration, unless this is a definition,
10710 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010711 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10712 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010713 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010714 }
10715
David Majnemer55890bf2013-06-11 03:51:23 +000010716 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010717 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010718 // except that a nested class or member class template can be declared
10719 // and then later defined.
10720 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10721 S->isDeclScope(PrevDecl)) {
10722 Diag(NameLoc, diag::ext_member_redeclared);
10723 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10724 }
10725
Douglas Gregor170512f2009-04-01 23:51:29 +000010726 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010727 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010728
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010729 // FIXME: In the future, return a variant or some other clue
10730 // for the consumer of this Decl to know it doesn't own it.
10731 // For our current ASTs this shouldn't be a problem, but will
10732 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010733 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010734 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010735 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010736
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010737 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010738 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010739 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010740 // If we're defining a specialization and the previous definition
10741 // is from an implicit instantiation, don't emit an error
10742 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010743 bool IsExplicitSpecializationAfterInstantiation = false;
10744 if (isExplicitSpecialization) {
10745 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10746 IsExplicitSpecializationAfterInstantiation =
10747 RD->getTemplateSpecializationKind() !=
10748 TSK_ExplicitSpecialization;
10749 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10750 IsExplicitSpecializationAfterInstantiation =
10751 ED->getTemplateSpecializationKind() !=
10752 TSK_ExplicitSpecialization;
10753 }
10754
10755 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010756 // A redeclaration in function prototype scope in C isn't
10757 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010758 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010759 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10760 else
10761 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010762 Diag(Def->getLocation(), diag::note_previous_definition);
10763 // If this is a redefinition, recover by making this
10764 // struct be anonymous, which will make any later
10765 // references get the previous definition.
10766 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010767 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010768 Invalid = true;
10769 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010770 } else {
10771 // If the type is currently being defined, complain
10772 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010773 const TagType *Tag
10774 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010775 if (Tag->isBeingDefined()) {
10776 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010777 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010778 diag::note_previous_definition);
10779 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010780 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010781 Invalid = true;
10782 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010783 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010784
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010785 // Okay, this is definition of a previously declared or referenced
10786 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010787 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010788 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010789 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000010790 // have a definition. Just create a new decl.
10791
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010792 } else {
10793 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000010794 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010795 // new decl/type. We set PrevDecl to NULL so that the entities
10796 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000010797 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000010798 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010799 // If we get here, we're going to create a new Decl. If PrevDecl
10800 // is non-NULL, it's a definition of the tag declared by
10801 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000010802
10803
10804 // Otherwise, PrevDecl is not a tag, but was found with tag
10805 // lookup. This is only actually possible in C++, where a few
10806 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010807 } else {
John McCalle87beb22010-04-23 18:46:30 +000010808 // Use a better diagnostic if an elaborated-type-specifier
10809 // found the wrong kind of type on the first
10810 // (non-redeclaration) lookup.
10811 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10812 !Previous.isForRedeclaration()) {
10813 unsigned Kind = 0;
10814 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010815 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10816 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010817 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10818 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10819 Invalid = true;
10820
10821 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +000010822 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10823 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000010824 // do nothing
10825
10826 // Diagnose implicit declarations introduced by elaborated types.
10827 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10828 unsigned Kind = 0;
10829 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010830 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10831 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010832 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10833 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10834 Invalid = true;
10835
10836 // Otherwise it's a declaration. Call out a particularly common
10837 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000010838 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10839 unsigned Kind = 0;
10840 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000010841 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000010842 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000010843 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10844 Invalid = true;
10845
10846 // Otherwise, diagnose.
10847 } else {
10848 // The tag name clashes with something else in the target scope,
10849 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010850 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000010851 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010852 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000010853 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010854 }
John McCalle87beb22010-04-23 18:46:30 +000010855
10856 // The existing declaration isn't relevant to us; we're in a
10857 // new scope, so clear out the previous declaration.
10858 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000010859 }
Chris Lattner18b19622007-01-22 07:39:13 +000010860 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000010861
Chris Lattner438e5012008-12-17 07:13:27 +000010862CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000010863
John McCall1f82f242009-11-18 22:49:29 +000010864 TagDecl *PrevDecl = 0;
10865 if (Previous.isSingleResult())
10866 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10867
Chris Lattnerbf0b7982007-01-23 04:27:41 +000010868 // If there is an identifier, use the location of the identifier as the
10869 // location of the decl, otherwise use the location of the struct/union
10870 // keyword.
10871 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000010872
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010873 // Otherwise, create a new declaration. If there is a previous
10874 // declaration of the same entity, the two will be linked via
10875 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000010876 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000010877
Douglas Gregor0bf31402010-10-08 23:50:27 +000010878 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010879 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000010880 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10881 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010882 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010883 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010884 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000010885 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010886 if (TUK != TUK_Definition && !Invalid) {
10887 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000010888 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10889 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010890 // C++0x: 7.2p2: opaque-enum-declaration.
10891 // Conflicts are diagnosed above. Do nothing.
10892 }
10893 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010894 Diag(Loc, diag::ext_forward_ref_enum_def)
10895 << New;
10896 Diag(Def->getLocation(), diag::note_previous_definition);
10897 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000010898 unsigned DiagID = diag::ext_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010899 if (getLangOpts().MicrosoftMode)
Francois Pichet488b4a72010-09-12 05:06:55 +000010900 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010901 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000010902 DiagID = diag::err_forward_ref_enum;
10903 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010904
10905 // If this is a forward-declared reference to an enumeration, make a
10906 // note of it; we won't actually be introducing the declaration into
10907 // the declaration context.
10908 if (TUK == TUK_Reference)
10909 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010910 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000010911 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000010912
10913 if (EnumUnderlying) {
10914 EnumDecl *ED = cast<EnumDecl>(New);
10915 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10916 ED->setIntegerTypeSourceInfo(TI);
10917 else
10918 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10919 ED->setPromotionType(ED->getIntegerType());
10920 }
10921
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000010922 } else {
10923 // struct/union/class
10924
Chris Lattner776fac82007-06-09 00:53:06 +000010925 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10926 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010927 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000010928 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010929 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010930 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010931
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010932 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000010933 StdBadAlloc = cast<CXXRecordDecl>(New);
10934 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010935 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010936 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000010937 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010938
John McCall3e11ebe2010-03-15 10:12:16 +000010939 // Maybe add qualifier info.
10940 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000010941 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010942 // If this is either a declaration or a definition, check the
10943 // nested-name-specifier against the current context. We don't do this
10944 // for explicit specializations, because they have similar checking
10945 // (with more specific diagnostics) in the call to
10946 // CheckMemberSpecialization, below.
10947 if (!isExplicitSpecialization &&
10948 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10949 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10950 Invalid = true;
10951
Douglas Gregor14454802011-02-25 02:25:35 +000010952 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000010953 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000010954 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000010955 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010956 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000010957 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000010958 }
10959 else
10960 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000010961 }
10962
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000010963 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10964 // Add alignment attributes if necessary; these attributes are checked when
10965 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010966 //
10967 // It is important for implementing the correct semantics that this
10968 // happen here (in act on tag decl). The #pragma pack stack is
10969 // maintained as a result of parser callbacks which can occur at
10970 // many points during the parsing of a struct declaration (because
10971 // the #pragma tokens are effectively skipped over during the
10972 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000010973 if (TUK == TUK_Definition) {
10974 AddAlignmentAttributesForRecord(RD);
10975 AddMsStructLayoutForRecord(RD);
10976 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010977 }
10978
Douglas Gregor21823bf2011-12-20 18:11:52 +000010979 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000010980 if (isExplicitSpecialization)
10981 Diag(New->getLocation(), diag::err_module_private_specialization)
10982 << 2
10983 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000010984 // __module_private__ does not apply to local classes. However, we only
10985 // diagnose this as an error when the declaration specifiers are
10986 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000010987 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000010988 New->setModulePrivate();
10989 }
10990
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010991 // If this is a specialization of a member class (of a class template),
10992 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000010993 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010994 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010995
Douglas Gregordee1be82009-01-17 00:42:38 +000010996 if (Invalid)
10997 New->setInvalidDecl();
10998
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010999 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011000 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011001
Douglas Gregordee1be82009-01-17 00:42:38 +000011002 // If we're declaring or defining a tag in function prototype scope
11003 // in C, note that this type can only be used within the function.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011004 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor658b9552009-01-09 22:42:13 +000011005 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11006
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011007 // Set the lexical context. If the tag has a C++ scope specifier, the
11008 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011009 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011010
John McCallaa74a0c2009-08-28 07:59:38 +000011011 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011012 // In Microsoft mode, a friend declaration also acts as a forward
11013 // declaration so we always pass true to setObjectOfFriendDecl to make
11014 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011015 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011016 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11017 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011018
Anders Carlsson5558ca12009-03-26 01:19:02 +000011019 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011020 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011021 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011022
John McCall9bb74a52009-07-31 02:45:11 +000011023 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011024 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011025
Chris Lattner18b19622007-01-22 07:39:13 +000011026 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011027 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011028 // We might be replacing an existing declaration in the lookup tables;
11029 // if so, borrow its access specifier.
11030 if (PrevDecl)
11031 New->setAccess(PrevDecl->getAccess());
11032
Sebastian Redl50c68252010-08-31 00:36:30 +000011033 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011034 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011035 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011036 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11037 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011038 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011039 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011040 PushOnScopeChains(New, S, !IsForwardReference);
11041 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011042 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011043
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011044 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011045 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011046 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011047
Douglas Gregor27821ce2009-07-07 16:35:42 +000011048 // If this is the C FILE type, notify the AST context.
11049 if (IdentifierInfo *II = New->getIdentifier())
11050 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011051 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011052 II->isStr("FILE"))
11053 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011054
James Molloy6f8780b2012-02-29 10:24:19 +000011055 // If we were in function prototype scope (and not in C++ mode), add this
11056 // tag to the list of decls to inject into the function definition scope.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011057 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy6f8780b2012-02-29 10:24:19 +000011058 InFunctionDeclarator && Name)
11059 DeclsInPrototypeScope.push_back(New);
11060
Rafael Espindolac67f2232012-05-10 02:50:16 +000011061 if (PrevDecl)
11062 mergeDeclAttributes(New, PrevDecl);
11063
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011064 // If there's a #pragma GCC visibility in scope, set the visibility of this
11065 // record.
11066 AddPushedVisibilityAttribute(New);
11067
Douglas Gregord6ab8742009-05-28 23:31:59 +000011068 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011069 // In C++, don't return an invalid declaration. We can't recover well from
11070 // the cases where we make the type anonymous.
11071 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011072}
Chris Lattner1300fb92007-01-23 23:42:53 +000011073
John McCall48871652010-08-21 09:40:31 +000011074void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011075 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011076 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011077
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011078 // Enter the tag context.
11079 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011080
11081 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011082
11083 // If there's a #pragma GCC visibility in scope, set the visibility of this
11084 // record.
11085 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011086}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011087
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011088Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011089 assert(isa<ObjCContainerDecl>(IDecl) &&
11090 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11091 DeclContext *OCD = cast<DeclContext>(IDecl);
11092 assert(getContainingDC(OCD) == CurContext &&
11093 "The next DeclContext should be lexically contained in the current one.");
11094 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011095 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011096}
11097
John McCall48871652010-08-21 09:40:31 +000011098void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011099 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011100 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011101 SourceLocation LBraceLoc) {
11102 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011103 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011104
John McCall1c7e6ec2009-12-20 07:58:13 +000011105 FieldCollector->StartClass();
11106
11107 if (!Record->getIdentifier())
11108 return;
11109
Anders Carlsson30f29442011-03-25 14:31:08 +000011110 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011111 Record->addAttr(new (Context)
11112 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11113
John McCall1c7e6ec2009-12-20 07:58:13 +000011114 // C++ [class]p2:
11115 // [...] The class-name is also inserted into the scope of the
11116 // class itself; this is known as the injected-class-name. For
11117 // purposes of access checking, the injected-class-name is treated
11118 // as if it were a public member name.
11119 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011120 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11121 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011122 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011123 /*PrevDecl=*/0,
11124 /*DelayTypeCreation=*/true);
11125 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011126 InjectedClassName->setImplicit();
11127 InjectedClassName->setAccess(AS_public);
11128 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11129 InjectedClassName->setDescribedClassTemplate(Template);
11130 PushOnScopeChains(InjectedClassName, S);
11131 assert(InjectedClassName->isInjectedClassName() &&
11132 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011133}
11134
John McCall48871652010-08-21 09:40:31 +000011135void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011136 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011137 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011138 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011139 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011140
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011141 // Make sure we "complete" the definition even it is invalid.
11142 if (Tag->isBeingDefined()) {
11143 assert(Tag->isInvalidDecl() && "We should already have completed it");
11144 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11145 RD->completeDefinition();
11146 }
11147
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011148 if (isa<CXXRecordDecl>(Tag))
11149 FieldCollector->FinishClass();
11150
11151 // Exit this scope of this tag's definition.
11152 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011153
11154 if (getCurLexicalContext()->isObjCContainer() &&
11155 Tag->getDeclContext()->isFileContext())
11156 Tag->setTopLevelDeclInObjCContainer();
11157
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011158 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011159 if (!Tag->isInvalidDecl())
11160 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011161}
Chris Lattner535b8302008-06-21 19:39:06 +000011162
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011163void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011164 // Exit this scope of this interface definition.
11165 PopDeclContext();
11166}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011167
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011168void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011169 assert(DC == CurContext && "Mismatch of container contexts");
11170 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011171 ActOnObjCContainerFinishDefinition();
11172}
11173
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011174void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11175 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011176 OriginalLexicalContext = 0;
11177}
11178
John McCall48871652010-08-21 09:40:31 +000011179void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011180 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011181 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011182 Tag->setInvalidDecl();
11183
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011184 // Make sure we "complete" the definition even it is invalid.
11185 if (Tag->isBeingDefined()) {
11186 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11187 RD->completeDefinition();
11188 }
11189
John McCall71ba5f22010-03-17 19:25:57 +000011190 // We're undoing ActOnTagStartDefinition here, not
11191 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11192 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011193
11194 PopDeclContext();
11195}
11196
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011197// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011198ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11199 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011200 QualType FieldTy, bool IsMsStruct,
11201 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011202 // Default to true; that shouldn't confuse checks for emptiness
11203 if (ZeroWidth)
11204 *ZeroWidth = true;
11205
Chris Lattner73bf7b42009-03-05 22:45:59 +000011206 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011207 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011208 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011209 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011210 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011211 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011212 if (FieldName)
11213 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11214 << FieldName << FieldTy << BitWidth->getSourceRange();
11215 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11216 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011217 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11218 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011219 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011220
11221 // If the bit-width is type- or value-dependent, don't try to check
11222 // it now.
11223 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011224 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011225
Anders Carlsson5df391e2008-12-06 20:33:04 +000011226 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011227 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11228 if (ICE.isInvalid())
11229 return ICE;
11230 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011231
Eli Friedmanc96d4962009-08-15 21:55:26 +000011232 if (Value != 0 && ZeroWidth)
11233 *ZeroWidth = false;
11234
Chris Lattner81ed6802008-12-12 04:56:04 +000011235 // Zero-width bitfield is ok for anonymous field.
11236 if (Value == 0 && FieldName)
11237 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011238
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011239 if (Value.isSigned() && Value.isNegative()) {
11240 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011241 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011242 << FieldName << Value.toString(10);
11243 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11244 << Value.toString(10);
11245 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011246
Douglas Gregor1efa4372009-03-11 18:59:21 +000011247 if (!FieldTy->isDependentType()) {
11248 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011249 if (Value.getZExtValue() > TypeSize) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011250 if (!getLangOpts().CPlusPlus || IsMsStruct) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011251 if (FieldName)
11252 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11253 << FieldName << (unsigned)Value.getZExtValue()
11254 << (unsigned)TypeSize;
11255
11256 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11257 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11258 }
11259
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011260 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011261 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11262 << FieldName << (unsigned)Value.getZExtValue()
11263 << (unsigned)TypeSize;
11264 else
11265 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11266 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011267 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011268 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011269
Richard Smithf4c51d92012-02-04 09:53:13 +000011270 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011271}
11272
Richard Smith938f40b2011-06-11 17:19:42 +000011273/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011274/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011275Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011276 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011277 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011278 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011279 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011280 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011281}
11282
11283/// HandleField - Analyze a field of a C struct or a C++ data member.
11284///
11285FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11286 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011287 Declarator &D, Expr *BitWidth,
11288 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011289 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011290 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011291 SourceLocation Loc = DeclStart;
11292 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011293
John McCall8cb7bdf2010-06-04 23:28:52 +000011294 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11295 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011296 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011297 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011298
Douglas Gregora02a72a2010-12-15 23:18:36 +000011299 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11300 UPPC_DataMemberType)) {
11301 D.setInvalidType();
11302 T = Context.IntTy;
11303 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11304 }
11305 }
11306
Matt Arsenault376f7202013-02-26 21:16:00 +000011307 // TR 18037 does not allow fields to be declared with address spaces.
11308 if (T.getQualifiers().hasAddressSpace()) {
11309 Diag(Loc, diag::err_field_with_address_space);
11310 D.setInvalidType();
11311 }
11312
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011313 // OpenCL 1.2 spec, s6.9 r:
11314 // The event type cannot be used to declare a structure or union field.
11315 if (LangOpts.OpenCL && T->isEventT()) {
11316 Diag(Loc, diag::err_event_t_struct_field);
11317 D.setInvalidType();
11318 }
11319
Richard Smithb1402ae2013-03-18 22:52:47 +000011320 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011321
Richard Smithb4a9e862013-04-12 22:46:28 +000011322 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11323 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11324 diag::err_invalid_thread)
11325 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011326
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011327 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011328 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011329 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11330 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011331 switch (Previous.getResultKind()) {
11332 case LookupResult::Found:
11333 case LookupResult::FoundUnresolvedValue:
11334 PrevDecl = Previous.getAsSingle<NamedDecl>();
11335 break;
11336
11337 case LookupResult::FoundOverloaded:
11338 PrevDecl = Previous.getRepresentativeDecl();
11339 break;
11340
11341 case LookupResult::NotFound:
11342 case LookupResult::NotFoundInCurrentInstantiation:
11343 case LookupResult::Ambiguous:
11344 break;
11345 }
11346 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011347
11348 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11349 // Maybe we will complain about the shadowed template parameter.
11350 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11351 // Just pretend that we didn't see the previous declaration.
11352 PrevDecl = 0;
11353 }
11354
Douglas Gregor1efa4372009-03-11 18:59:21 +000011355 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11356 PrevDecl = 0;
11357
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011358 bool Mutable
11359 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011360 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011361 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011362 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011363 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011364
11365 if (NewFD->isInvalidDecl())
11366 Record->setInvalidDecl();
11367
Douglas Gregor3baa6702011-09-12 16:11:24 +000011368 if (D.getDeclSpec().isModulePrivateSpecified())
11369 NewFD->setModulePrivate();
11370
Douglas Gregor1efa4372009-03-11 18:59:21 +000011371 if (NewFD->isInvalidDecl() && PrevDecl) {
11372 // Don't introduce NewFD into scope; there's already something
11373 // with the same name in the same scope.
11374 } else if (II) {
11375 PushOnScopeChains(NewFD, S);
11376 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011377 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011378
11379 return NewFD;
11380}
11381
11382/// \brief Build a new FieldDecl and check its well-formedness.
11383///
11384/// This routine builds a new FieldDecl given the fields name, type,
11385/// record, etc. \p PrevDecl should refer to any previous declaration
11386/// with the same name and in the same scope as the field to be
11387/// created.
11388///
11389/// \returns a new FieldDecl.
11390///
Mike Stump11289f42009-09-09 15:08:12 +000011391/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011392FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011393 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011394 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011395 bool Mutable, Expr *BitWidth,
11396 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011397 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011398 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011399 Declarator *D) {
11400 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011401 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011402 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011403
Douglas Gregor1efa4372009-03-11 18:59:21 +000011404 // If we receive a broken type, recover by assuming 'int' and
11405 // marking this declaration as invalid.
11406 if (T.isNull()) {
11407 InvalidDecl = true;
11408 T = Context.IntTy;
11409 }
11410
Eli Friedmand0e8de22009-12-07 00:22:08 +000011411 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011412 if (!EltTy->isDependentType()) {
11413 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11414 // Fields of incomplete type force their record to be invalid.
11415 Record->setInvalidDecl();
11416 InvalidDecl = true;
11417 } else {
11418 NamedDecl *Def;
11419 EltTy->isIncompleteType(&Def);
11420 if (Def && Def->isInvalidDecl()) {
11421 Record->setInvalidDecl();
11422 InvalidDecl = true;
11423 }
11424 }
John McCall2677e102010-08-16 23:42:35 +000011425 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011426
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011427 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11428 if (BitWidth && getLangOpts().OpenCL) {
11429 Diag(Loc, diag::err_opencl_bitfields);
11430 InvalidDecl = true;
11431 }
11432
Steve Naroff8eeeb132007-05-08 21:09:37 +000011433 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11434 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011435 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011436 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011437 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011438
11439 TypeSourceInfo *FixedTInfo =
11440 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11441 SizeIsNegative,
11442 Oversized);
11443 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011444 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011445 TInfo = FixedTInfo;
11446 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011447 } else {
11448 if (SizeIsNegative)
11449 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011450 else if (Oversized.getBoolValue())
11451 Diag(Loc, diag::err_array_too_large)
11452 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011453 else
11454 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011455 InvalidDecl = true;
11456 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011457 }
Mike Stump11289f42009-09-09 15:08:12 +000011458
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011459 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011460 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11461 diag::err_abstract_type_in_decl,
11462 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011463 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011464
Eli Friedmanc96d4962009-08-15 21:55:26 +000011465 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011466 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011467 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011468 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11469 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011470 if (!BitWidth) {
11471 InvalidDecl = true;
11472 BitWidth = 0;
11473 ZeroWidth = false;
11474 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011475 }
Mike Stump11289f42009-09-09 15:08:12 +000011476
John McCallb1cd7da2010-06-04 08:34:12 +000011477 // Check that 'mutable' is consistent with the type of the declaration.
11478 if (!InvalidDecl && Mutable) {
11479 unsigned DiagID = 0;
11480 if (T->isReferenceType())
11481 DiagID = diag::err_mutable_reference;
11482 else if (T.isConstQualified())
11483 DiagID = diag::err_mutable_const;
11484
11485 if (DiagID) {
11486 SourceLocation ErrLoc = Loc;
11487 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11488 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11489 Diag(ErrLoc, DiagID);
11490 Mutable = false;
11491 InvalidDecl = true;
11492 }
11493 }
11494
Abramo Bagnaradff19302011-03-08 08:55:46 +000011495 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011496 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011497 if (InvalidDecl)
11498 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011499
Douglas Gregor1efa4372009-03-11 18:59:21 +000011500 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11501 Diag(Loc, diag::err_duplicate_member) << II;
11502 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11503 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011504 }
11505
David Blaikiebbafb8a2012-03-11 07:00:24 +000011506 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011507 if (Record->isUnion()) {
11508 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11509 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11510 if (RDecl->getDefinition()) {
11511 // C++ [class.union]p1: An object of a class with a non-trivial
11512 // constructor, a non-trivial copy constructor, a non-trivial
11513 // destructor, or a non-trivial copy assignment operator
11514 // cannot be a member of a union, nor can an array of such
11515 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011516 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011517 NewFD->setInvalidDecl();
11518 }
11519 }
11520
11521 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011522 // the program is ill-formed, except when compiling with MSVC extensions
11523 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011524 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011525 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11526 diag::ext_union_member_of_reference_type :
11527 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011528 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011529 if (!getLangOpts().MicrosoftExt)
11530 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011531 }
11532 }
11533 }
11534
Douglas Gregor1efa4372009-03-11 18:59:21 +000011535 // FIXME: We need to pass in the attributes given an AST
11536 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011537 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011538 // FIXME: The current scope is almost... but not entirely... correct here.
11539 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011540
Richard Smith848e1f12013-02-01 08:12:08 +000011541 if (NewFD->hasAttrs())
11542 CheckAlignasUnderalignment(NewFD);
11543 }
11544
John McCall31168b02011-06-15 23:02:42 +000011545 // In auto-retain/release, infer strong retension for fields of
11546 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011547 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011548 NewFD->setInvalidDecl();
11549
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011550 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011551 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011552
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011553 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011554 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011555}
11556
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011557bool Sema::CheckNontrivialField(FieldDecl *FD) {
11558 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011559 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011560
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011561 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11562 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011563
11564 QualType EltTy = Context.getBaseElementType(FD->getType());
11565 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011566 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011567 if (RDecl->getDefinition()) {
11568 // We check for copy constructors before constructors
11569 // because otherwise we'll never get complaints about
11570 // copy constructors.
11571
11572 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011573 // We're required to check for any non-trivial constructors. Since the
11574 // implicit default constructor is suppressed if there are any
11575 // user-declared constructors, we just need to check that there is a
11576 // trivial default constructor and a trivial copy constructor. (We don't
11577 // worry about move constructors here, since this is a C++98 check.)
11578 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011579 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011580 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011581 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011582 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011583 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011584 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011585 member = CXXDestructor;
11586
11587 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011588 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011589 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011590 // Objective-C++ ARC: it is an error to have a non-trivial field of
11591 // a union. However, system headers in Objective-C programs
11592 // occasionally have Objective-C lifetime objects within unions,
11593 // and rather than cause the program to fail, we make those
11594 // members unavailable.
11595 SourceLocation Loc = FD->getLocation();
11596 if (getSourceManager().isInSystemHeader(Loc)) {
11597 if (!FD->hasAttr<UnavailableAttr>())
11598 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +000011599 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +000011600 return false;
11601 }
11602 }
Richard Smithf720df02011-10-19 20:41:51 +000011603
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011604 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011605 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11606 diag::err_illegal_union_or_anon_struct_member)
11607 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011608 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011609 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011610 }
11611 }
11612 }
Richard Smith92f241f2012-12-08 02:53:02 +000011613
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011614 return false;
11615}
11616
Mike Stump11289f42009-09-09 15:08:12 +000011617/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011618/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011619static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011620TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011621 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011622 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011623 case tok::objc_private: return ObjCIvarDecl::Private;
11624 case tok::objc_public: return ObjCIvarDecl::Public;
11625 case tok::objc_protected: return ObjCIvarDecl::Protected;
11626 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011627 }
11628}
11629
Mike Stump11289f42009-09-09 15:08:12 +000011630/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011631/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011632Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011633 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011634 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011635 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011636
Fariborz Jahaniande615832008-04-10 23:32:45 +000011637 IdentifierInfo *II = D.getIdentifier();
11638 Expr *BitWidth = (Expr*)BitfieldWidth;
11639 SourceLocation Loc = DeclStart;
11640 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011641
Fariborz Jahaniande615832008-04-10 23:32:45 +000011642 // FIXME: Unnamed fields can be handled in various different ways, for
11643 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011644
John McCall8cb7bdf2010-06-04 23:28:52 +000011645 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11646 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011647
Fariborz Jahaniande615832008-04-10 23:32:45 +000011648 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011649 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011650 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011651 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011652 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011653 } else {
11654 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011655
Fariborz Jahaniande615832008-04-10 23:32:45 +000011656 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011657
Fariborz Jahaniande615832008-04-10 23:32:45 +000011658 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011659 if (T->isReferenceType()) {
11660 Diag(Loc, diag::err_ivar_reference_type);
11661 D.setInvalidType();
11662 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011663 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11664 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011665 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011666 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011667 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011668 }
Mike Stump11289f42009-09-09 15:08:12 +000011669
Ted Kremenek73295fa2008-07-23 18:04:17 +000011670 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011671 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011672 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11673 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011674 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011675 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011676 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11677 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011678 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011679 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011680 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011681 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011682 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011683 EnclosingContext = IMPDecl->getClassInterface();
11684 assert(EnclosingContext && "Implementation has no class interface!");
11685 }
11686 else
11687 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011688 } else {
11689 if (ObjCCategoryDecl *CDecl =
11690 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011691 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011692 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011693 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011694 }
11695 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011696 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011697 }
Mike Stump11289f42009-09-09 15:08:12 +000011698
Ted Kremenek73295fa2008-07-23 18:04:17 +000011699 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011700 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11701 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011702 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011703
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011704 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011705 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011706 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011707 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011708 && !isa<TagDecl>(PrevDecl)) {
11709 Diag(Loc, diag::err_duplicate_member) << II;
11710 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11711 NewID->setInvalidDecl();
11712 }
11713 }
11714
Ted Kremenek73295fa2008-07-23 18:04:17 +000011715 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011716 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011717
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011718 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011719 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011720
John McCall31168b02011-06-15 23:02:42 +000011721 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011722 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011723 NewID->setInvalidDecl();
11724
Douglas Gregor3baa6702011-09-12 16:11:24 +000011725 if (D.getDeclSpec().isModulePrivateSpecified())
11726 NewID->setModulePrivate();
11727
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011728 if (II) {
11729 // FIXME: When interfaces are DeclContexts, we'll need to add
11730 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011731 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011732 IdResolver.AddDecl(NewID);
11733 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011734
John McCall5fb5df92012-06-20 06:18:46 +000011735 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011736 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011737 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011738
John McCall48871652010-08-21 09:40:31 +000011739 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011740}
11741
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011742/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011743/// class and class extensions. For every class \@interface and class
11744/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011745/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011746void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011747 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011748 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011749 return;
11750
11751 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11752 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11753
Richard Smithcaf33902011-10-10 18:28:20 +000011754 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011755 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011756 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011757 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011758 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011759 if (!CD->IsClassExtension())
11760 return;
11761 }
11762 // No need to add this to end of @implementation.
11763 else
11764 return;
11765 }
11766 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011767 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11768 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011769
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011770 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011771 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011772 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011773 Context.getTrivialTypeSourceInfo(Context.CharTy,
11774 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011775 ObjCIvarDecl::Private, BW,
11776 true);
11777 AllIvarDecls.push_back(Ivar);
11778}
11779
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011780void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11781 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11782 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000011783 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000011784
Eric Christopher7457aaf2012-07-19 22:22:51 +000011785 // If this is an Objective-C @implementation or category and we have
11786 // new fields here we should reset the layout of the interface since
11787 // it will now change.
11788 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11789 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11790 switch (DC->getKind()) {
11791 default: break;
11792 case Decl::ObjCCategory:
11793 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11794 break;
11795 case Decl::ObjCImplementation:
11796 Context.
11797 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11798 break;
11799 }
11800 }
11801
Eli Friedmana7679412012-02-07 05:00:47 +000011802 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11803
11804 // Start counting up the number of named members; make sure to include
11805 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000011806 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000011807 if (Record) {
11808 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11809 e = Record->decls_end(); i != e; i++) {
11810 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11811 if (IFD->getDeclName())
11812 ++NumNamedMembers;
11813 }
11814 }
11815
11816 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011817 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000011818
John McCall31168b02011-06-15 23:02:42 +000011819 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011820 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000011821 i != end; ++i) {
11822 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000011823
Chris Lattner720a0542007-01-25 00:44:24 +000011824 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000011825 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000011826
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011827 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000011828 // Remember all fields written by the user.
11829 RecFields.push_back(FD);
11830 }
Mike Stump11289f42009-09-09 15:08:12 +000011831
Chris Lattner73bf7b42009-03-05 22:45:59 +000011832 // If the field is already invalid for some reason, don't emit more
11833 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011834 if (FD->isInvalidDecl()) {
11835 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000011836 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000011837 }
Mike Stump11289f42009-09-09 15:08:12 +000011838
Douglas Gregorac1fb652009-03-24 19:52:54 +000011839 // C99 6.7.2.1p2:
11840 // A structure or union shall not contain a member with
11841 // incomplete or function type (hence, a structure shall not
11842 // contain an instance of itself, but may contain a pointer to
11843 // an instance of itself), except that the last member of a
11844 // structure with more than one named member may have incomplete
11845 // array type; such a structure (and any union containing,
11846 // possibly recursively, a member that is such a structure)
11847 // shall not be a member of a structure or an element of an
11848 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000011849 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011850 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000011851 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011852 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000011853 FD->setInvalidDecl();
11854 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000011855 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000011856 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000011857 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000011858 ((getLangOpts().MicrosoftExt ||
11859 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000011860 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011861 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000011862 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000011863 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000011864 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000011865 unsigned DiagID = 0;
11866 if (Record->isUnion())
11867 DiagID = getLangOpts().MicrosoftExt
11868 ? diag::ext_flexible_array_union_ms
11869 : getLangOpts().CPlusPlus
11870 ? diag::ext_flexible_array_union_gnu
11871 : diag::err_flexible_array_union;
11872 else if (Fields.size() == 1)
11873 DiagID = getLangOpts().MicrosoftExt
11874 ? diag::ext_flexible_array_empty_aggregate_ms
11875 : getLangOpts().CPlusPlus
11876 ? diag::ext_flexible_array_empty_aggregate_gnu
11877 : NumNamedMembers < 1
11878 ? diag::err_flexible_array_empty_aggregate
11879 : 0;
11880
11881 if (DiagID)
11882 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11883 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000011884 // While the layout of types that contain virtual bases is not specified
11885 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11886 // virtual bases after the derived members. This would make a flexible
11887 // array member declared at the end of an object not adjacent to the end
11888 // of the type.
11889 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11890 if (RD->getNumVBases() != 0)
11891 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11892 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000011893 if (!getLangOpts().C99)
11894 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11895 << FD->getDeclName() << Record->getTagKind();
11896
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011897 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +000011898 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011899 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000011900 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011901 FD->setInvalidDecl();
11902 EnclosingDecl->setInvalidDecl();
11903 continue;
11904 }
Chris Lattner720a0542007-01-25 00:44:24 +000011905 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000011906 if (Record)
11907 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000011908 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000011909 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000011910 diag::err_field_incomplete)) {
11911 // Incomplete type
11912 FD->setInvalidDecl();
11913 EnclosingDecl->setInvalidDecl();
11914 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011915 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000011916 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11917 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011918 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000011919 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000011920 } else {
11921 // If this is a struct/class and this is not the last element, reject
11922 // it. Note that GCC supports variable sized arrays in the middle of
11923 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000011924 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000011925 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000011926 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000011927 else {
11928 // We support flexible arrays at the end of structs in
11929 // other structs as an extension.
11930 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11931 << FD->getDeclName();
11932 if (Record)
11933 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000011934 }
Chris Lattner720a0542007-01-25 00:44:24 +000011935 }
11936 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000011937 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11938 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11939 diag::err_abstract_type_in_decl,
11940 AbstractIvarType)) {
11941 // Ivars can not have abstract class types
11942 FD->setInvalidDecl();
11943 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000011944 if (Record && FDTTy->getDecl()->hasObjectMember())
11945 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000011946 if (Record && FDTTy->getDecl()->hasVolatileMember())
11947 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000011948 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011949 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000011950 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11951 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11952 QualType T = Context.getObjCObjectPointerType(FD->getType());
11953 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011954 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11955 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11956 // It's an error in ARC if a field has lifetime.
11957 // We don't want to report this in a system header, though,
11958 // so we just make the field unavailable.
11959 // FIXME: that's really not sufficient; we need to make the type
11960 // itself invalid to, say, initialize or copy.
11961 QualType T = FD->getType();
11962 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11963 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11964 SourceLocation loc = FD->getLocation();
11965 if (getSourceManager().isInSystemHeader(loc)) {
11966 if (!FD->hasAttr<UnavailableAttr>()) {
11967 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11968 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +000011969 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011970 } else {
11971 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000011972 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000011973 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011974 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000011975 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011976 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011977 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000011978 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011979 if (FD->getType()->isObjCObjectPointerType() ||
11980 FD->getType().isObjCGCStrong())
11981 Record->setHasObjectMember(true);
11982 else if (Context.getAsArrayType(FD->getType())) {
11983 QualType BaseType = Context.getBaseElementType(FD->getType());
11984 if (BaseType->isRecordType() &&
11985 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000011986 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011987 else if (BaseType->isObjCObjectPointerType() ||
11988 BaseType.isObjCGCStrong())
11989 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000011990 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000011991 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000011992 if (Record && FD->getType().isVolatileQualified())
11993 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000011994 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011995 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000011996 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000011997 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011998
Chris Lattner82625602007-01-24 02:26:21 +000011999 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012000 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012001 bool Completed = false;
12002 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12003 if (!CXXRecord->isInvalidDecl()) {
12004 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012005 for (CXXRecordDecl::conversion_iterator
12006 I = CXXRecord->conversion_begin(),
12007 E = CXXRecord->conversion_end(); I != E; ++I)
12008 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012009
12010 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012011 if (CXXRecord->hasUserDeclaredDestructor()) {
12012 // Adjust user-defined destructor exception spec.
12013 if (getLangOpts().CPlusPlus11)
12014 AdjustDestructorExceptionSpec(CXXRecord,
12015 CXXRecord->getDestructor());
12016
12017 // The Microsoft ABI requires that we perform the destructor body
12018 // checks (i.e. operator delete() lookup) at every declaration, as
12019 // any translation unit may need to emit a deleting destructor.
12020 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12021 CheckDestructor(CXXRecord->getDestructor());
12022 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012023
Douglas Gregor8fb95122010-09-29 00:15:42 +000012024 // Add any implicitly-declared members to this class.
12025 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12026
12027 // If we have virtual base classes, we may end up finding multiple
12028 // final overriders for a given virtual function. Check for this
12029 // problem now.
12030 if (CXXRecord->getNumVBases()) {
12031 CXXFinalOverriderMap FinalOverriders;
12032 CXXRecord->getFinalOverriders(FinalOverriders);
12033
12034 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12035 MEnd = FinalOverriders.end();
12036 M != MEnd; ++M) {
12037 for (OverridingMethods::iterator SO = M->second.begin(),
12038 SOEnd = M->second.end();
12039 SO != SOEnd; ++SO) {
12040 assert(SO->second.size() > 0 &&
12041 "Virtual function without overridding functions?");
12042 if (SO->second.size() == 1)
12043 continue;
12044
12045 // C++ [class.virtual]p2:
12046 // In a derived class, if a virtual member function of a base
12047 // class subobject has more than one final overrider the
12048 // program is ill-formed.
12049 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012050 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012051 Diag(M->first->getLocation(),
12052 diag::note_overridden_virtual_function);
12053 for (OverridingMethods::overriding_iterator
12054 OM = SO->second.begin(),
12055 OMEnd = SO->second.end();
12056 OM != OMEnd; ++OM)
12057 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012058 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012059
12060 Record->setInvalidDecl();
12061 }
12062 }
12063 CXXRecord->completeDefinition(&FinalOverriders);
12064 Completed = true;
12065 }
12066 }
12067 }
12068 }
12069
12070 if (!Completed)
12071 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012072
Richard Smith848e1f12013-02-01 08:12:08 +000012073 if (Record->hasAttrs())
12074 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012075
Serge Pavlov3cb80222013-11-14 02:13:03 +000012076 // Check if the structure/union declaration is a type that can have zero
12077 // size in C. For C this is a language extension, for C++ it may cause
12078 // compatibility problems.
12079 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012080 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012081 CheckForZeroSize = true;
12082 } else {
12083 // For C++ filter out types that cannot be referenced in C code.
12084 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12085 CheckForZeroSize =
12086 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12087 !CXXRecord->isDependentType() &&
12088 CXXRecord->isCLike();
12089 }
12090 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012091 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012092 bool IsEmpty = true;
12093 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012094 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012095 E = Record->field_end();
12096 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12097 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012098 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012099 if (I->getBitWidthValue(Context) > 0)
12100 ZeroSize = false;
12101 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012102 ++NonBitFields;
12103 QualType FieldType = I->getType();
12104 if (FieldType->isIncompleteType() ||
12105 !Context.getTypeSizeInChars(FieldType).isZero())
12106 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012107 }
12108 }
12109
Serge Pavlov3cb80222013-11-14 02:13:03 +000012110 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12111 // allowed in C++, but warn if its declaration is inside
12112 // extern "C" block.
12113 if (ZeroSize) {
12114 Diag(RecLoc, getLangOpts().CPlusPlus ?
12115 diag::warn_zero_size_struct_union_in_extern_c :
12116 diag::warn_zero_size_struct_union_compat)
12117 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12118 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012119
Serge Pavlov3cb80222013-11-14 02:13:03 +000012120 // Structs without named members are extension in C (C99 6.7.2.1p7),
12121 // but are accepted by GCC.
12122 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12123 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12124 diag::ext_no_named_members_in_struct_union)
12125 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012126 }
12127 }
Chris Lattner622c1932008-02-06 00:51:33 +000012128 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012129 ObjCIvarDecl **ClsFields =
12130 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012131 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012132 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012133 // Add ivar's to class's DeclContext.
12134 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12135 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012136 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012137 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012138 // Must enforce the rule that ivars in the base classes may not be
12139 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012140 if (ID->getSuperClass())
12141 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012142 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012143 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012144 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012145 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12146 // Ivar declared in @implementation never belongs to the implementation.
12147 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012148 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012149 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012150 IMPDecl->setIvarLBraceLoc(LBrac);
12151 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012152 } else if (ObjCCategoryDecl *CDecl =
12153 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012154 // case of ivars in class extension; all other cases have been
12155 // reported as errors elsewhere.
12156 // FIXME. Class extension does not have a LocEnd field.
12157 // CDecl->setLocEnd(RBrac);
12158 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012159 // Diagnose redeclaration of private ivars.
12160 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012161 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012162 if (IDecl) {
12163 if (const ObjCIvarDecl *ClsIvar =
12164 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12165 Diag(ClsFields[i]->getLocation(),
12166 diag::err_duplicate_ivar_declaration);
12167 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12168 continue;
12169 }
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012170 for (ObjCInterfaceDecl::known_extensions_iterator
12171 Ext = IDecl->known_extensions_begin(),
12172 ExtEnd = IDecl->known_extensions_end();
12173 Ext != ExtEnd; ++Ext) {
12174 if (const ObjCIvarDecl *ClsExtIvar
12175 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012176 Diag(ClsFields[i]->getLocation(),
12177 diag::err_duplicate_ivar_declaration);
12178 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12179 continue;
12180 }
12181 }
12182 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012183 ClsFields[i]->setLexicalDeclContext(CDecl);
12184 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012185 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012186 CDecl->setIvarLBraceLoc(LBrac);
12187 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012188 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012189 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012190
12191 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012192 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012193}
12194
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012195/// \brief Determine whether the given integral value is representable within
12196/// the given type T.
12197static bool isRepresentableIntegerValue(ASTContext &Context,
12198 llvm::APSInt &Value,
12199 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012200 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012201 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012202
Douglas Gregor0bf31402010-10-08 23:50:27 +000012203 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012204 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012205 --BitWidth;
12206 return Value.getActiveBits() <= BitWidth;
12207 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012208 return Value.getMinSignedBits() <= BitWidth;
12209}
12210
12211// \brief Given an integral type, return the next larger integral type
12212// (or a NULL type of no such type exists).
12213static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12214 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12215 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012216 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012217 const unsigned NumTypes = 4;
12218 QualType SignedIntegralTypes[NumTypes] = {
12219 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12220 };
12221 QualType UnsignedIntegralTypes[NumTypes] = {
12222 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12223 Context.UnsignedLongLongTy
12224 };
12225
12226 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012227 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12228 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012229 for (unsigned I = 0; I != NumTypes; ++I)
12230 if (Context.getTypeSize(Types[I]) > BitWidth)
12231 return Types[I];
12232
12233 return QualType();
12234}
12235
Douglas Gregor954f6b272009-03-17 19:05:46 +000012236EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12237 EnumConstantDecl *LastEnumConst,
12238 SourceLocation IdLoc,
12239 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012240 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012241 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012242 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012243 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012244
12245 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12246 Val = 0;
12247
Eli Friedman7c6515a2011-12-06 00:10:34 +000012248 if (Val)
12249 Val = DefaultLvalueConversion(Val).take();
12250
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012251 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012252 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012253 EltTy = Context.DependentTy;
12254 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012255 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012256 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012257 !getLangOpts().MicrosoftMode) {
Richard Smithf8379a02012-01-18 23:55:52 +000012258 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12259 // constant-expression in the enumerator-definition shall be a converted
12260 // constant expression of the underlying type.
12261 EltTy = Enum->getIntegerType();
12262 ExprResult Converted =
12263 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12264 CCEK_Enumerator);
12265 if (Converted.isInvalid())
12266 Val = 0;
12267 else
12268 Val = Converted.take();
12269 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012270 !(Val = VerifyIntegerConstantExpression(Val,
12271 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012272 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012273 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012274 if (Enum->isFixed()) {
12275 EltTy = Enum->getIntegerType();
12276
Richard Smithf8379a02012-01-18 23:55:52 +000012277 // In Obj-C and Microsoft mode, require the enumeration value to be
12278 // representable in the underlying type of the enumeration. In C++11,
12279 // we perform a non-narrowing conversion as part of converted constant
12280 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012281 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012282 if (getLangOpts().MicrosoftMode) {
Francois Picheta3108062010-10-18 15:01:13 +000012283 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012284 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012285 } else
12286 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012287 } else
John Wiegley01296292011-04-08 18:41:53 +000012288 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012289 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012290 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012291 // If the underlying type is not fixed, the type of each enumerator
12292 // is the type of its initializing value:
12293 // - If an initializer is specified for an enumerator, the
12294 // initializing value has the same type as the expression.
12295 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012296 } else {
12297 // C99 6.7.2.2p2:
12298 // The expression that defines the value of an enumeration constant
12299 // shall be an integer constant expression that has a value
12300 // representable as an int.
12301
12302 // Complain if the value is not representable in an int.
12303 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12304 Diag(IdLoc, diag::ext_enum_value_not_int)
12305 << EnumVal.toString(10) << Val->getSourceRange()
12306 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12307 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12308 // Force the type of the expression to 'int'.
12309 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12310 }
12311 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012312 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012313 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012314 }
12315 }
Mike Stump11289f42009-09-09 15:08:12 +000012316
Douglas Gregor954f6b272009-03-17 19:05:46 +000012317 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012318 if (Enum->isDependentType())
12319 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012320 else if (!LastEnumConst) {
12321 // C++0x [dcl.enum]p5:
12322 // If the underlying type is not fixed, the type of each enumerator
12323 // is the type of its initializing value:
12324 // - If no initializer is specified for the first enumerator, the
12325 // initializing value has an unspecified integral type.
12326 //
12327 // GCC uses 'int' for its unspecified integral type, as does
12328 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012329 if (Enum->isFixed()) {
12330 EltTy = Enum->getIntegerType();
12331 }
12332 else {
12333 EltTy = Context.IntTy;
12334 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012335 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012336 // Assign the last value + 1.
12337 EnumVal = LastEnumConst->getInitVal();
12338 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012339 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012340
12341 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012342 if (EnumVal < LastEnumConst->getInitVal()) {
12343 // C++0x [dcl.enum]p5:
12344 // If the underlying type is not fixed, the type of each enumerator
12345 // is the type of its initializing value:
12346 //
12347 // - Otherwise the type of the initializing value is the same as
12348 // the type of the initializing value of the preceding enumerator
12349 // unless the incremented value is not representable in that type,
12350 // in which case the type is an unspecified integral type
12351 // sufficient to contain the incremented value. If no such type
12352 // exists, the program is ill-formed.
12353 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012354 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012355 // There is no integral type larger enough to represent this
12356 // value. Complain, then allow the value to wrap around.
12357 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012358 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012359 ++EnumVal;
12360 if (Enum->isFixed())
12361 // When the underlying type is fixed, this is ill-formed.
12362 Diag(IdLoc, diag::err_enumerator_wrapped)
12363 << EnumVal.toString(10)
12364 << EltTy;
12365 else
12366 Diag(IdLoc, diag::warn_enumerator_too_large)
12367 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012368 } else {
12369 EltTy = T;
12370 }
12371
12372 // Retrieve the last enumerator's value, extent that type to the
12373 // type that is supposed to be large enough to represent the incremented
12374 // value, then increment.
12375 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012376 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012377 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012378 ++EnumVal;
12379
12380 // If we're not in C++, diagnose the overflow of enumerator values,
12381 // which in C99 means that the enumerator value is not representable in
12382 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12383 // permits enumerator values that are representable in some larger
12384 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012385 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012386 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012387 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012388 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12389 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12390 Diag(IdLoc, diag::ext_enum_value_not_int)
12391 << EnumVal.toString(10) << 1;
12392 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012393 }
12394 }
Mike Stump11289f42009-09-09 15:08:12 +000012395
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012396 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012397 // Make the enumerator value match the signedness and size of the
12398 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012399 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012400 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012401 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012402
Douglas Gregor954f6b272009-03-17 19:05:46 +000012403 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012404 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012405}
12406
12407
John McCall811a0f52010-10-22 23:36:17 +000012408Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12409 SourceLocation IdLoc, IdentifierInfo *Id,
12410 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012411 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012412 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012413 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012414 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012415
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012416 // The scope passed in may not be a decl scope. Zip up the scope tree until
12417 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012418 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012419
Chris Lattner8116d1b2007-01-25 22:38:29 +000012420 // Verify that there isn't already something declared with this name in this
12421 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012422 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012423 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012424 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012425 // Maybe we will complain about the shadowed template parameter.
12426 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12427 // Just pretend that we didn't see the previous declaration.
12428 PrevDecl = 0;
12429 }
12430
12431 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012432 // When in C++, we may get a TagDecl with the same name; in this case the
12433 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012434 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012435 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012436 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012437 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012438 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012439 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012440 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012441 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012442 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012443 }
12444 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012445
Aaron Ballman24a10472012-07-19 03:12:23 +000012446 // C++ [class.mem]p15:
12447 // If T is the name of a class, then each of the following shall have a name
12448 // different from T:
12449 // - every enumerator of every member of class T that is an unscoped
12450 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012451 if (CXXRecordDecl *Record
12452 = dyn_cast<CXXRecordDecl>(
12453 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012454 if (!TheEnumDecl->isScoped() &&
12455 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012456 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12457
John McCall811a0f52010-10-22 23:36:17 +000012458 EnumConstantDecl *New =
12459 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012460
John McCall553c0792010-01-23 00:46:32 +000012461 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012462 // Process attributes.
12463 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12464
12465 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012466 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012467 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012468 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012469
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012470 ActOnDocumentableDecl(New);
12471
John McCall48871652010-08-21 09:40:31 +000012472 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012473}
12474
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012475// Returns true when the enum initial expression does not trigger the
12476// duplicate enum warning. A few common cases are exempted as follows:
12477// Element2 = Element1
12478// Element2 = Element1 + 1
12479// Element2 = Element1 - 1
12480// Where Element2 and Element1 are from the same enum.
12481static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12482 Expr *InitExpr = ECD->getInitExpr();
12483 if (!InitExpr)
12484 return true;
12485 InitExpr = InitExpr->IgnoreImpCasts();
12486
12487 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12488 if (!BO->isAdditiveOp())
12489 return true;
12490 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12491 if (!IL)
12492 return true;
12493 if (IL->getValue() != 1)
12494 return true;
12495
12496 InitExpr = BO->getLHS();
12497 }
12498
12499 // This checks if the elements are from the same enum.
12500 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12501 if (!DRE)
12502 return true;
12503
12504 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12505 if (!EnumConstant)
12506 return true;
12507
12508 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12509 Enum)
12510 return true;
12511
12512 return false;
12513}
12514
12515struct DupKey {
12516 int64_t val;
12517 bool isTombstoneOrEmptyKey;
12518 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12519 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12520};
12521
12522static DupKey GetDupKey(const llvm::APSInt& Val) {
12523 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12524 false);
12525}
12526
12527struct DenseMapInfoDupKey {
12528 static DupKey getEmptyKey() { return DupKey(0, true); }
12529 static DupKey getTombstoneKey() { return DupKey(1, true); }
12530 static unsigned getHashValue(const DupKey Key) {
12531 return (unsigned)(Key.val * 37);
12532 }
12533 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12534 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12535 LHS.val == RHS.val;
12536 }
12537};
12538
12539// Emits a warning when an element is implicitly set a value that
12540// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012541static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12542 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012543 QualType EnumType) {
12544 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12545 Enum->getLocation()) ==
12546 DiagnosticsEngine::Ignored)
12547 return;
12548 // Avoid anonymous enums
12549 if (!Enum->getIdentifier())
12550 return;
12551
12552 // Only check for small enums.
12553 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12554 return;
12555
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012556 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12557 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012558
12559 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12560 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12561 ValueToVectorMap;
12562
12563 DuplicatesVector DupVector;
12564 ValueToVectorMap EnumMap;
12565
12566 // Populate the EnumMap with all values represented by enum constants without
12567 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012568 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012569 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012570
12571 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12572 // this constant. Skip this enum since it may be ill-formed.
12573 if (!ECD) {
12574 return;
12575 }
12576
12577 if (ECD->getInitExpr())
12578 continue;
12579
12580 DupKey Key = GetDupKey(ECD->getInitVal());
12581 DeclOrVector &Entry = EnumMap[Key];
12582
12583 // First time encountering this value.
12584 if (Entry.isNull())
12585 Entry = ECD;
12586 }
12587
12588 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012589 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012590 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12591 if (!ValidDuplicateEnum(ECD, Enum))
12592 continue;
12593
12594 DupKey Key = GetDupKey(ECD->getInitVal());
12595
12596 DeclOrVector& Entry = EnumMap[Key];
12597 if (Entry.isNull())
12598 continue;
12599
12600 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12601 // Ensure constants are different.
12602 if (D == ECD)
12603 continue;
12604
12605 // Create new vector and push values onto it.
12606 ECDVector *Vec = new ECDVector();
12607 Vec->push_back(D);
12608 Vec->push_back(ECD);
12609
12610 // Update entry to point to the duplicates vector.
12611 Entry = Vec;
12612
12613 // Store the vector somewhere we can consult later for quick emission of
12614 // diagnostics.
12615 DupVector.push_back(Vec);
12616 continue;
12617 }
12618
12619 ECDVector *Vec = Entry.get<ECDVector*>();
12620 // Make sure constants are not added more than once.
12621 if (*Vec->begin() == ECD)
12622 continue;
12623
12624 Vec->push_back(ECD);
12625 }
12626
12627 // Emit diagnostics.
12628 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12629 DupVectorEnd = DupVector.end();
12630 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12631 ECDVector *Vec = *DupVectorIter;
12632 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12633
12634 // Emit warning for one enum constant.
12635 ECDVector::iterator I = Vec->begin();
12636 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12637 << (*I)->getName() << (*I)->getInitVal().toString(10)
12638 << (*I)->getSourceRange();
12639 ++I;
12640
12641 // Emit one note for each of the remaining enum constants with
12642 // the same value.
12643 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12644 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12645 << (*I)->getName() << (*I)->getInitVal().toString(10)
12646 << (*I)->getSourceRange();
12647 delete Vec;
12648 }
12649}
12650
Mike Stump6814d1c2009-05-16 07:06:02 +000012651void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012652 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012653 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012654 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012655 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012656 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012657
12658 if (Attr)
12659 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012660
Eli Friedmand0e60972009-12-11 01:34:50 +000012661 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012662 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012663 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012664 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012665 if (!ECD) continue;
12666
12667 ECD->setType(EnumType);
12668 }
12669
John McCall9aa35be2010-05-06 08:49:23 +000012670 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012671 return;
12672 }
12673
Chris Lattner67933c02007-08-28 05:10:31 +000012674 // TODO: If the result value doesn't fit in an int, it must be a long or long
12675 // long value. ISO C does not support this, but GCC does as an extension,
12676 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012677 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12678 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12679 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012680
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012681 // Verify that all the values are okay, compute the size of the values, and
12682 // reverse the list.
12683 unsigned NumNegativeBits = 0;
12684 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012685
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012686 // Keep track of whether all elements have type int.
12687 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012688
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012689 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012690 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012691 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012692 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012693
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012694 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012695
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012696 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012697 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012698 NumPositiveBits = std::max(NumPositiveBits,
12699 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012700 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012701 NumNegativeBits = std::max(NumNegativeBits,
12702 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012703
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012704 // Keep track of whether every enum element has type int (very commmon).
12705 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012706 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012707 }
Mike Stump11289f42009-09-09 15:08:12 +000012708
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012709 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012710 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012711 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012712
John McCall56774992009-12-09 09:09:27 +000012713 // C++0x N3000 [conv.prom]p3:
12714 // An rvalue of an unscoped enumeration type whose underlying
12715 // type is not fixed can be converted to an rvalue of the first
12716 // of the following types that can represent all the values of
12717 // the enumeration: int, unsigned int, long int, unsigned long
12718 // int, long long int, or unsigned long long int.
12719 // C99 6.4.4.3p2:
12720 // An identifier declared as an enumeration constant has type int.
12721 // The C99 rule is modified by a gcc extension
12722 QualType BestPromotionType;
12723
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012724 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012725 // -fshort-enums is the equivalent to specifying the packed attribute on all
12726 // enum definitions.
12727 if (LangOpts.ShortEnums)
12728 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012729
Douglas Gregor0bf31402010-10-08 23:50:27 +000012730 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012731 BestType = Enum->getIntegerType();
12732 if (BestType->isPromotableIntegerType())
12733 BestPromotionType = Context.getPromotedIntegerType(BestType);
12734 else
12735 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012736 // We don't need to set BestWidth, because BestType is going to be the type
12737 // of the enumerators, but we do anyway because otherwise some compilers
12738 // warn that it might be used uninitialized.
12739 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012740 }
12741 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012742 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012743 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012744 // If it's packed, check also if it fits a char or a short.
12745 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012746 BestType = Context.SignedCharTy;
12747 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012748 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012749 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012750 BestType = Context.ShortTy;
12751 BestWidth = ShortWidth;
12752 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012753 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012754 BestWidth = IntWidth;
12755 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012756 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012757
John McCall56774992009-12-09 09:09:27 +000012758 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012759 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012760 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012761 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012762
Chris Lattner3a370bf2007-08-29 17:31:48 +000012763 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012764 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12765 BestType = Context.LongLongTy;
12766 }
12767 }
John McCall56774992009-12-09 09:09:27 +000012768 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012769 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012770 // If there is no negative value, figure out the smallest type that fits
12771 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012772 // If it's packed, check also if it fits a char or a short.
12773 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012774 BestType = Context.UnsignedCharTy;
12775 BestPromotionType = Context.IntTy;
12776 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012777 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012778 BestType = Context.UnsignedShortTy;
12779 BestPromotionType = Context.IntTy;
12780 BestWidth = ShortWidth;
12781 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012782 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012783 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000012784 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012785 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012786 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012787 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000012788 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012789 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012790 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012791 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012792 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000012793 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012794 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012795 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012796 "How could an initializer get larger than ULL?");
12797 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012798 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012799 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012800 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012801 }
12802 }
Mike Stump11289f42009-09-09 15:08:12 +000012803
Chris Lattner3a370bf2007-08-29 17:31:48 +000012804 // Loop over all of the enumerator constants, changing their types to match
12805 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012806 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000012807 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012808 if (!ECD) continue; // Already issued a diagnostic.
12809
12810 // Standard C says the enumerators have int type, but we allow, as an
12811 // extension, the enumerators to be larger than int size. If each
12812 // enumerator value fits in an int, type it as an int, otherwise type it the
12813 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12814 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000012815
12816 // Determine whether the value fits into an int.
12817 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012818
12819 // If it fits into an integer type, force it. Otherwise force it to match
12820 // the enum decl type.
12821 QualType NewTy;
12822 unsigned NewWidth;
12823 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000012824 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000012825 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012826 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000012827 NewTy = Context.IntTy;
12828 NewWidth = IntWidth;
12829 NewSign = true;
12830 } else if (ECD->getType() == BestType) {
12831 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000012832 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012833 // C++ [dcl.enum]p4: Following the closing brace of an
12834 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012835 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012836 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012837 continue;
12838 } else {
12839 NewTy = BestType;
12840 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012841 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012842 }
12843
12844 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000012845 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012846 InitVal.setIsSigned(NewSign);
12847 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000012848
Chris Lattner3a370bf2007-08-29 17:31:48 +000012849 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000012850 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000012851 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000012852 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000012853 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000012854 ECD->getInitExpr(),
12855 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000012856 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000012857 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012858 // C++ [dcl.enum]p4: Following the closing brace of an
12859 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012860 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012861 ECD->setType(EnumType);
12862 else
12863 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012864 }
Mike Stump11289f42009-09-09 15:08:12 +000012865
John McCall9aa35be2010-05-06 08:49:23 +000012866 Enum->completeDefinition(BestType, BestPromotionType,
12867 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000012868
12869 // If we're declaring a function, ensure this decl isn't forgotten about -
12870 // it needs to go into the function scope.
12871 if (InFunctionDeclarator)
12872 DeclsInPrototypeScope.push_back(Enum);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012873
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012874 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000012875
12876 // Now that the enum type is defined, ensure it's not been underaligned.
12877 if (Enum->hasAttrs())
12878 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012879}
Chris Lattner1300fb92007-01-23 23:42:53 +000012880
Abramo Bagnara348823a2011-03-03 14:20:18 +000012881Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12882 SourceLocation StartLoc,
12883 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000012884 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000012885
Douglas Gregor278f52e2009-05-30 00:08:05 +000012886 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000012887 AsmString, StartLoc,
12888 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012889 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000012890 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000012891}
Eli Friedman5ed51982009-06-05 02:44:36 +000012892
Douglas Gregor22d09742012-01-03 18:04:46 +000012893DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12894 SourceLocation ImportLoc,
12895 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000012896 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000012897 Module::AllVisible,
12898 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000012899 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000012900 return true;
12901
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012902 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000012903 Module *ModCheck = Mod;
12904 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12905 // If we've run out of module parents, just drop the remaining identifiers.
12906 // We need the length to be consistent.
12907 if (!ModCheck)
12908 break;
12909 ModCheck = ModCheck->Parent;
12910
12911 IdentifierLocs.push_back(Path[I].second);
12912 }
12913
12914 ImportDecl *Import = ImportDecl::Create(Context,
12915 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000012916 AtLoc.isValid()? AtLoc : ImportLoc,
12917 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000012918 Context.getTranslationUnitDecl()->addDecl(Import);
12919 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000012920}
12921
Richard Smithce587f52013-11-15 04:24:58 +000012922void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
12923 // FIXME: Should we synthesize an ImportDecl here?
12924 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
12925 /*Complain=*/true);
12926}
12927
Douglas Gregorc147b0b2013-01-12 01:29:50 +000012928void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12929 // Create the implicit import declaration.
12930 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12931 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12932 Loc, Mod, Loc);
12933 TU->addDecl(ImportD);
12934 Consumer.HandleImplicitImportDecl(ImportD);
12935
12936 // Make the module visible.
Douglas Gregorfb912652013-03-20 21:10:35 +000012937 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12938 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000012939}
12940
David Chisnall0867d9c2012-02-18 16:12:34 +000012941void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12942 IdentifierInfo* AliasName,
12943 SourceLocation PragmaLoc,
12944 SourceLocation NameLoc,
12945 SourceLocation AliasNameLoc) {
12946 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12947 LookupOrdinaryName);
12948 AsmLabelAttr *Attr =
12949 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
David Chisnall0867d9c2012-02-18 16:12:34 +000012950
12951 if (PrevDecl)
12952 PrevDecl->addAttr(Attr);
12953 else
12954 (void)ExtnameUndeclaredIdentifiers.insert(
12955 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12956}
12957
Eli Friedman5ed51982009-06-05 02:44:36 +000012958void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12959 SourceLocation PragmaLoc,
12960 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012961 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000012962
Eli Friedman5ed51982009-06-05 02:44:36 +000012963 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +000012964 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +000012965 } else {
12966 (void)WeakUndeclaredIdentifiers.insert(
12967 std::pair<IdentifierInfo*,WeakInfo>
12968 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000012969 }
Eli Friedman5ed51982009-06-05 02:44:36 +000012970}
12971
12972void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12973 IdentifierInfo* AliasName,
12974 SourceLocation PragmaLoc,
12975 SourceLocation NameLoc,
12976 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012977 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12978 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000012979 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000012980
Eli Friedman5ed51982009-06-05 02:44:36 +000012981 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000012982 if (!PrevDecl->hasAttr<AliasAttr>())
12983 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000012984 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000012985 } else {
12986 (void)WeakUndeclaredIdentifiers.insert(
12987 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000012988 }
Eli Friedman5ed51982009-06-05 02:44:36 +000012989}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012990
12991Decl *Sema::getObjCDeclContext() const {
12992 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12993}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000012994
12995AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000012996 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000012997 // If we are within an Objective-C method, we should consult
12998 // both the availability of the method as well as the
12999 // enclosing class. If the class is (say) deprecated,
13000 // the entire method is considered deprecated from the
13001 // purpose of checking if the current context is deprecated.
13002 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13003 AvailabilityResult R = MD->getAvailability();
13004 if (R != AR_Available)
13005 return R;
13006 D = MD->getClassInterface();
13007 }
13008 // If we are within an Objective-c @implementation, it
13009 // gets the same availability context as the @interface.
13010 else if (const ObjCImplementationDecl *ID =
13011 dyn_cast<ObjCImplementationDecl>(D)) {
13012 D = ID->getClassInterface();
13013 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013014 return D->getAvailability();
13015}