blob: 6d46903c58b503d37555094de0fe87ca18637324 [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;
Alp Tokerbfa39342014-01-14 12:51:41 +0000470 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000471 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000472
473 Diag(SS->getRange().getBegin(), DiagID)
Aaron Ballman691e2272014-01-03 14:48:20 +0000474 << SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000475 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000476 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000477 SuggestedType = ActOnTypenameType(S, SourceLocation(),
478 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000479 } else {
480 assert(SS && SS->isInvalid() &&
481 "Invalid scope specifier has already been diagnosed");
482 }
483
484 return true;
485}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000486
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000487/// \brief Determine whether the given result set contains either a type name
488/// or
489static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000490 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000491 NextToken.is(tok::less);
492
493 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
494 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
495 return true;
496
497 if (CheckTemplate && isa<TemplateDecl>(*I))
498 return true;
499 }
500
501 return false;
502}
503
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000504static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
505 Scope *S, CXXScopeSpec &SS,
506 IdentifierInfo *&Name,
507 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000508 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
509 SemaRef.LookupParsedName(R, S, &SS);
510 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000511 const char *TagName = 0;
512 const char *FixItTagName = 0;
513 switch (Tag->getTagKind()) {
514 case TTK_Class:
515 TagName = "class";
516 FixItTagName = "class ";
517 break;
518
519 case TTK_Enum:
520 TagName = "enum";
521 FixItTagName = "enum ";
522 break;
523
524 case TTK_Struct:
525 TagName = "struct";
526 FixItTagName = "struct ";
527 break;
528
Joao Matosdc86f942012-08-31 18:45:21 +0000529 case TTK_Interface:
530 TagName = "__interface";
531 FixItTagName = "__interface ";
532 break;
533
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000534 case TTK_Union:
535 TagName = "union";
536 FixItTagName = "union ";
537 break;
538 }
539
540 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
541 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
542 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
543
Richard Smithaa31b4b2012-09-06 01:37:56 +0000544 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
545 I != IEnd; ++I)
546 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
547 << Name << TagName;
548
549 // Replace lookup results with just the tag decl.
550 Result.clear(Sema::LookupTagName);
551 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000552 return true;
553 }
554
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000555 return false;
556}
557
Richard Smith4f605af2012-08-18 00:55:03 +0000558/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
559static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
560 QualType T, SourceLocation NameLoc) {
561 ASTContext &Context = S.Context;
562
563 TypeLocBuilder Builder;
564 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
565
566 T = S.getElaboratedType(ETK_None, SS, T);
567 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
568 ElabTL.setElaboratedKeywordLoc(SourceLocation());
569 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
570 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
571}
572
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000573Sema::NameClassification Sema::ClassifyName(Scope *S,
574 CXXScopeSpec &SS,
575 IdentifierInfo *&Name,
576 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000577 const Token &NextToken,
578 bool IsAddressOfOperand,
579 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000580 DeclarationNameInfo NameInfo(Name, NameLoc);
581 ObjCMethodDecl *CurMethod = getCurMethodDecl();
582
583 if (NextToken.is(tok::coloncolon)) {
584 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
585 QualType(), false, SS, 0, false);
586
587 }
588
589 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
590 LookupParsedName(Result, S, &SS, !CurMethod);
591
592 // Perform lookup for Objective-C instance variables (including automatically
593 // synthesized instance variables), if we're in an Objective-C method.
594 // FIXME: This lookup really, really needs to be folded in to the normal
595 // unqualified lookup mechanism.
596 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
597 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000598 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000599 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000600 }
601
602 bool SecondTry = false;
603 bool IsFilteredTemplateName = false;
604
605Corrected:
606 switch (Result.getResultKind()) {
607 case LookupResult::NotFound:
608 // If an unqualified-id is followed by a '(', then we have a function
609 // call.
610 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
611 // In C++, this is an ADL-only call.
612 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000613 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000614 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
615
616 // C90 6.3.2.2:
617 // If the expression that precedes the parenthesized argument list in a
618 // function call consists solely of an identifier, and if no
619 // declaration is visible for this identifier, the identifier is
620 // implicitly declared exactly as if, in the innermost block containing
621 // the function call, the declaration
622 //
623 // extern int identifier ();
624 //
625 // appeared.
626 //
627 // We also allow this in C99 as an extension.
628 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
629 Result.addDecl(D);
630 Result.resolveKind();
631 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
632 }
633 }
634
635 // In C, we first see whether there is a tag type by the same name, in
636 // which case it's likely that the user just forget to write "enum",
637 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000638 if (!getLangOpts().CPlusPlus && !SecondTry &&
639 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
640 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000641 }
642
643 // Perform typo correction to determine if there is another name that is
644 // close to this name.
Richard Smith4f605af2012-08-18 00:55:03 +0000645 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000646 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000647 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000648 Result.getLookupKind(), S,
Richard Smith4f605af2012-08-18 00:55:03 +0000649 &SS, *CCC)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000650 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
651 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000652
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000653 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000654 NamedDecl *UnderlyingFirstDecl
655 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000656 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000657 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000658 UnqualifiedDiag = diag::err_no_template_suggest;
659 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000660 } else if (UnderlyingFirstDecl &&
661 (isa<TypeDecl>(UnderlyingFirstDecl) ||
662 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
663 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000664 UnqualifiedDiag = diag::err_unknown_typename_suggest;
665 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
666 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000667
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000668 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000669 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000670 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000671 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
672 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000673 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000674 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
675 << Name << computeDeclContext(SS, false)
676 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000677 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000678
679 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000680 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000681
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000682 // Typo correction corrected to a keyword.
683 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000684 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000685
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000686 // Also update the LookupResult...
687 // FIXME: This should probably go away at some point
688 Result.clear();
689 Result.setLookupName(Corrected.getCorrection());
Richard Smithf9b15102013-08-17 00:46:16 +0000690 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000691 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000692
693 // If we found an Objective-C instance variable, let
694 // LookupInObjCMethod build the appropriate expression to
695 // reference the ivar.
696 // FIXME: This is a gross hack.
697 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
698 Result.clear();
699 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000700 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000701 }
702
703 goto Corrected;
704 }
705 }
706
707 // We failed to correct; just fall through and let the parser deal with it.
708 Result.suppressDiagnostics();
709 return NameClassification::Unknown();
710
Abramo Bagnara7945c982012-01-27 09:46:47 +0000711 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000712 // We performed name lookup into the current instantiation, and there were
713 // dependent bases, so we treat this result the same way as any other
714 // dependent nested-name-specifier.
715
716 // C++ [temp.res]p2:
717 // A name used in a template declaration or definition and that is
718 // dependent on a template-parameter is assumed not to name a type
719 // unless the applicable name lookup finds a type name or the name is
720 // qualified by the keyword typename.
721 //
722 // FIXME: If the next token is '<', we might want to ask the parser to
723 // perform some heroics to see if we actually have a
724 // template-argument-list, which would indicate a missing 'template'
725 // keyword here.
Richard Smith4f605af2012-08-18 00:55:03 +0000726 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
727 NameInfo, IsAddressOfOperand,
728 /*TemplateArgs=*/0);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000729 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000730
731 case LookupResult::Found:
732 case LookupResult::FoundOverloaded:
733 case LookupResult::FoundUnresolvedValue:
734 break;
735
736 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000737 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000738 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000739 // C++ [temp.local]p3:
740 // A lookup that finds an injected-class-name (10.2) can result in an
741 // ambiguity in certain cases (for example, if it is found in more than
742 // one base class). If all of the injected-class-names that are found
743 // refer to specializations of the same class template, and if the name
744 // is followed by a template-argument-list, the reference refers to the
745 // class template itself and not a specialization thereof, and is not
746 // ambiguous.
747 //
748 // This filtering can make an ambiguous result into an unambiguous one,
749 // so try again after filtering out template names.
750 FilterAcceptableTemplateNames(Result);
751 if (!Result.isAmbiguous()) {
752 IsFilteredTemplateName = true;
753 break;
754 }
755 }
756
757 // Diagnose the ambiguity and return an error.
758 return NameClassification::Error();
759 }
760
David Blaikiebbafb8a2012-03-11 07:00:24 +0000761 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000762 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
763 // C++ [temp.names]p3:
764 // After name lookup (3.4) finds that a name is a template-name or that
765 // an operator-function-id or a literal- operator-id refers to a set of
766 // overloaded functions any member of which is a function template if
767 // this is followed by a <, the < is always taken as the delimiter of a
768 // template-argument-list and never as the less-than operator.
769 if (!IsFilteredTemplateName)
770 FilterAcceptableTemplateNames(Result);
771
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000772 if (!Result.empty()) {
773 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000774 bool IsVarTemplate;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000775 TemplateName Template;
776 if (Result.end() - Result.begin() > 1) {
777 IsFunctionTemplate = true;
778 Template = Context.getOverloadedTemplateName(Result.begin(),
779 Result.end());
780 } else {
781 TemplateDecl *TD
782 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
783 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000784 IsVarTemplate = isa<VarTemplateDecl>(TD);
785
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000786 if (SS.isSet() && !SS.isInvalid())
787 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000788 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000789 TD);
790 else
791 Template = TemplateName(TD);
792 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000793
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000794 if (IsFunctionTemplate) {
795 // Function templates always go through overload resolution, at which
796 // point we'll perform the various checks (e.g., accessibility) we need
797 // to based on which function we selected.
798 Result.suppressDiagnostics();
799
800 return NameClassification::FunctionTemplate(Template);
801 }
Larisse Voufo39a1e502013-08-06 01:03:05 +0000802
803 return IsVarTemplate ? NameClassification::VarTemplate(Template)
804 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000805 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000806 }
Richard Smith4f605af2012-08-18 00:55:03 +0000807
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000808 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000809 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
810 DiagnoseUseOfDecl(Type, NameLoc);
811 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000812 if (SS.isNotEmpty())
813 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000814 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000815 }
Richard Smith4f605af2012-08-18 00:55:03 +0000816
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000817 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
818 if (!Class) {
819 // FIXME: It's unfortunate that we don't have a Type node for handling this.
820 if (ObjCCompatibleAliasDecl *Alias
821 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
822 Class = Alias->getClassInterface();
823 }
824
825 if (Class) {
826 DiagnoseUseOfDecl(Class, NameLoc);
827
828 if (NextToken.is(tok::period)) {
829 // Interface. <something> is parsed as a property reference expression.
830 // Just return "unknown" as a fall-through for now.
831 Result.suppressDiagnostics();
832 return NameClassification::Unknown();
833 }
834
835 QualType T = Context.getObjCInterfaceType(Class);
836 return ParsedType::make(T);
837 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000838
Richard Smith4f605af2012-08-18 00:55:03 +0000839 // We can have a type template here if we're classifying a template argument.
840 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
841 return NameClassification::TypeTemplate(
842 TemplateName(cast<TemplateDecl>(FirstDecl)));
843
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000844 // Check for a tag type hidden by a non-type decl in a few cases where it
845 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000846 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
847 if ((NextToken.is(tok::identifier) ||
848 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
849 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
850 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
851 DiagnoseUseOfDecl(Type, NameLoc);
852 QualType T = Context.getTypeDeclType(Type);
853 if (SS.isNotEmpty())
854 return buildNestedType(*this, SS, T, NameLoc);
855 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000856 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000857
Richard Smith4f605af2012-08-18 00:55:03 +0000858 if (FirstDecl->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000859 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000860
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000861 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
862 return BuildDeclarationNameExpr(SS, Result, ADL);
863}
864
John McCall5ed6e8f2009-08-18 00:00:49 +0000865// Determines the context to return to after temporarily entering a
866// context. This depends in an unnecessarily complicated way on the
867// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000868DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000869
John McCall5ed6e8f2009-08-18 00:00:49 +0000870 // Functions defined inline within classes aren't parsed until we've
871 // finished parsing the top-level class, so the top-level class is
872 // the context we'll need to return to.
Faisal Valibb9071e2013-12-04 22:43:08 +0000873 // A Lambda call operator whose parent is a class must not be treated
874 // as an inline member function. A Lambda can be used legally
875 // either as an in-class member initializer or a default argument. These
876 // are parsed once the class has been marked complete and so the containing
877 // context would be the nested class (when the lambda is defined in one);
878 // If the class is not complete, then the lambda is being used in an
879 // ill-formed fashion (such as to specify the width of a bit-field, or
880 // in an array-bound) - in which case we still want to return the
881 // lexically containing DC (which could be a nested class).
882 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +0000883 DC = DC->getLexicalParent();
884
885 // A function not defined within a class will always return to its
886 // lexical context.
887 if (!isa<CXXRecordDecl>(DC))
888 return DC;
889
890 // A C++ inline method/friend is parsed *after* the topmost class
891 // it was declared in is fully parsed ("complete"); the topmost
892 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000893 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000894 DC = RD;
895
896 // Return the declaration context of the topmost class the inline method is
897 // declared in.
898 return DC;
899 }
900
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000901 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000902}
903
Douglas Gregor91f84212008-12-11 16:49:14 +0000904void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000905 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000906 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000907 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000908 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000909}
910
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000911void Sema::PopDeclContext() {
912 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000913
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000914 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000915 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000916}
917
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000918/// EnterDeclaratorContext - Used when we must lookup names in the context
919/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000920///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000921void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000922 // C++0x [basic.lookup.unqual]p13:
923 // A name used in the definition of a static data member of class
924 // X (after the qualified-id of the static member) is looked up as
925 // if the name was used in a member function of X.
926 // C++0x [basic.lookup.unqual]p14:
927 // If a variable member of a namespace is defined outside of the
928 // scope of its namespace then any name used in the definition of
929 // the variable member (after the declarator-id) is looked up as
930 // if the definition of the variable member occurred in its
931 // namespace.
932 // Both of these imply that we should push a scope whose context
933 // is the semantic context of the declaration. We can't use
934 // PushDeclContext here because that context is not necessarily
935 // lexically contained in the current context. Fortunately,
936 // the containing scope should have the appropriate information.
937
938 assert(!S->getEntity() && "scope already has entity");
939
940#ifndef NDEBUG
941 Scope *Ancestor = S->getParent();
942 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
943 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
944#endif
945
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000946 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000947 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000948}
949
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000950void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000951 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000952
John McCall6df5fef2009-12-19 10:49:29 +0000953 // Switch back to the lexical context. The safety of this is
954 // enforced by an assert in EnterDeclaratorContext.
955 Scope *Ancestor = S->getParent();
956 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +0000957 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +0000958
959 // We don't need to do anything with the scope, which is going to
960 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000961}
962
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000963
964void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
965 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
966 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
967 // We assume that the caller has already called
968 // ActOnReenterTemplateScope
969 FD = TFD->getTemplatedDecl();
970 }
971 if (!FD)
972 return;
973
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000974 // Same implementation as PushDeclContext, but enters the context
975 // from the lexical parent, rather than the top-level class.
976 assert(CurContext == FD->getLexicalParent() &&
977 "The next DeclContext should be lexically contained in the current one.");
978 CurContext = FD;
979 S->setEntity(CurContext);
980
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000981 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
982 ParmVarDecl *Param = FD->getParamDecl(P);
983 // If the parameter has an identifier, then add it to the scope
984 if (Param->getIdentifier()) {
985 S->AddDecl(Param);
986 IdResolver.AddDecl(Param);
987 }
988 }
989}
990
991
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000992void Sema::ActOnExitFunctionContext() {
993 // Same implementation as PopDeclContext, but returns to the lexical parent,
994 // rather than the top-level class.
995 assert(CurContext && "DeclContext imbalance!");
996 CurContext = CurContext->getLexicalParent();
997 assert(CurContext && "Popped translation unit!");
998}
999
1000
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001001/// \brief Determine whether we allow overloading of the function
1002/// PrevDecl with another declaration.
1003///
1004/// This routine determines whether overloading is possible, not
1005/// whether some new function is actually an overload. It will return
1006/// true in C++ (where we can always provide overloads) or, as an
1007/// extension, in C when the previous function is already an
1008/// overloaded function declaration or has the "overloadable"
1009/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001010static bool AllowOverloadingOfFunction(LookupResult &Previous,
1011 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001012 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001013 return true;
1014
John McCall1f82f242009-11-18 22:49:29 +00001015 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001016 return true;
1017
John McCall1f82f242009-11-18 22:49:29 +00001018 return (Previous.getResultKind() == LookupResult::Found
1019 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001020}
1021
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001022/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001023void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001024 // Move up the scope chain until we find the nearest enclosing
1025 // non-transparent context. The declaration will be introduced into this
1026 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001027 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001028 S = S->getParent();
1029
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001030 // Add scoped declarations into their context, so that they can be
1031 // found later. Declarations without a context won't be inserted
1032 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001033 if (AddToContext)
1034 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001035
Richard Smith541b38b2013-09-20 01:15:31 +00001036 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1037 // are function-local declarations.
1038 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001039 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001040 D->getLexicalDeclContext()->getRedeclContext()) &&
1041 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001042 return;
1043
1044 // Template instantiations should also not be pushed into scope.
1045 if (isa<FunctionDecl>(D) &&
1046 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001047 return;
1048
John McCall9f3059a2009-10-09 21:13:30 +00001049 // If this replaces anything in the current scope,
1050 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1051 IEnd = IdResolver.end();
1052 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001053 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1054 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001055 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001056
John McCall9f3059a2009-10-09 21:13:30 +00001057 // Should only need to replace one decl.
1058 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001059 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001060 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061
John McCall48871652010-08-21 09:40:31 +00001062 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001063
1064 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1065 // Implicitly-generated labels may end up getting generated in an order that
1066 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1067 // the label at the appropriate place in the identifier chain.
1068 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001069 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001070 if (IDC == CurContext) {
1071 if (!S->isDeclScope(*I))
1072 continue;
1073 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001074 break;
1075 }
1076
Douglas Gregor46c04e72011-03-16 16:39:03 +00001077 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001078 } else {
1079 IdResolver.AddDecl(D);
1080 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001081}
1082
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001083void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1084 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1085 TUScope->AddDecl(D);
1086}
1087
Richard Smith1c34fb72013-08-13 18:18:50 +00001088bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001089 bool AllowInlineNamespace) {
1090 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001091}
1092
John McCallcc14d1f2010-08-24 08:50:51 +00001093Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1094 DeclContext *TargetDC = DC->getPrimaryContext();
1095 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001096 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001097 if (ScopeDC->getPrimaryContext() == TargetDC)
1098 return S;
1099 } while ((S = S->getParent()));
1100
1101 return 0;
1102}
1103
John McCall1f82f242009-11-18 22:49:29 +00001104static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1105 DeclContext*,
1106 ASTContext&);
1107
1108/// Filters out lookup results that don't fall within the given scope
1109/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001110void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001111 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001112 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001113 LookupResult::Filter F = R.makeFilter();
1114 while (F.hasNext()) {
1115 NamedDecl *D = F.next();
1116
Richard Smith72bcaec2013-12-05 04:30:04 +00001117 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001118 continue;
1119
Richard Smith72bcaec2013-12-05 04:30:04 +00001120 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001121 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001122
John McCall1f82f242009-11-18 22:49:29 +00001123 F.erase();
1124 }
1125
1126 F.done();
1127}
1128
1129static bool isUsingDecl(NamedDecl *D) {
1130 return isa<UsingShadowDecl>(D) ||
1131 isa<UnresolvedUsingTypenameDecl>(D) ||
1132 isa<UnresolvedUsingValueDecl>(D);
1133}
1134
1135/// Removes using shadow declarations from the lookup results.
1136static void RemoveUsingDecls(LookupResult &R) {
1137 LookupResult::Filter F = R.makeFilter();
1138 while (F.hasNext())
1139 if (isUsingDecl(F.next()))
1140 F.erase();
1141
1142 F.done();
1143}
1144
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001145/// \brief Check for this common pattern:
1146/// @code
1147/// class S {
1148/// S(const S&); // DO NOT IMPLEMENT
1149/// void operator=(const S&); // DO NOT IMPLEMENT
1150/// };
1151/// @endcode
1152static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1153 // FIXME: Should check for private access too but access is set after we get
1154 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001155 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001156 return false;
1157
1158 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1159 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001160 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1161 return Method->isCopyAssignmentOperator();
1162 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001163}
1164
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001165// We need this to handle
1166//
1167// typedef struct {
1168// void *foo() { return 0; }
1169// } A;
1170//
1171// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1172// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001173// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001174// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001175// Callers should verify at the end of the TU if it D has external linkage or
1176// not.
1177bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1178 const DeclContext *DC = D->getDeclContext();
1179 while (!DC->isTranslationUnit()) {
1180 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1181 if (!RD->hasNameForLinkage())
1182 return true;
1183 }
1184 DC = DC->getParent();
1185 }
1186
Rafael Espindola3ae00052013-05-13 00:12:11 +00001187 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001188}
1189
Eli Friedman5ef21752013-09-10 03:05:56 +00001190// FIXME: This needs to be refactored; some other isInMainFile users want
1191// these semantics.
1192static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1193 if (S.TUKind != TU_Complete)
1194 return false;
1195 return S.SourceMgr.isInMainFile(Loc);
1196}
1197
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001198bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1199 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001200
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001201 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1202 return false;
1203
1204 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001205 if (D->getDeclContext()->isDependentContext() ||
1206 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001207 return false;
1208
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001209 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001210 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1211 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001212
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001213 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1214 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1215 return false;
1216 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001217 // 'static inline' functions are defined in headers; don't warn.
1218 if (FD->isInlineSpecified() &&
1219 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001220 return false;
1221 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001222
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001223 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001224 Context.DeclMustBeEmitted(FD))
1225 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001226 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001227 // Constants and utility variables are defined in headers with internal
1228 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1229 // like "inline".)
1230 if (!isMainFileLoc(*this, VD->getLocation()))
1231 return false;
1232
Eli Friedman5ef21752013-09-10 03:05:56 +00001233 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001234 return false;
1235
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001236 if (VD->isStaticDataMember() &&
1237 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1238 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001239 } else {
1240 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001241 }
1242
John McCalld37d35b2010-10-27 01:41:35 +00001243 // Only warn for unused decls internal to the translation unit.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001244 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001245}
1246
1247void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001248 if (!D)
1249 return;
1250
1251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001252 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001253 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1254 return; // First should already be in the vector.
1255 }
1256
1257 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001258 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001259 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1260 return; // First should already be in the vector.
1261 }
1262
David Blaikie3d8edc22012-05-26 05:35:39 +00001263 if (ShouldWarnIfUnusedFileScopedDecl(D))
1264 UnusedFileScopedDecls.push_back(D);
1265}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001266
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001267static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001268 if (D->isInvalidDecl())
1269 return false;
1270
Ted Kremenekce0e3f82014-01-09 20:19:45 +00001271 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1272 D->hasAttr<ObjCPreciseLifetimeAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001273 return false;
John McCall67da35c2010-02-04 22:26:26 +00001274
Chris Lattnercab02a62011-02-17 20:34:02 +00001275 if (isa<LabelDecl>(D))
1276 return true;
1277
John McCall67da35c2010-02-04 22:26:26 +00001278 // White-list anything that isn't a local variable.
1279 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1280 !D->getDeclContext()->isFunctionOrMethod())
1281 return false;
1282
1283 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001285
1286 // White-list anything with an __attribute__((unused)) type.
1287 QualType Ty = VD->getType();
1288
1289 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001290 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001291 if (TT->getDecl()->hasAttr<UnusedAttr>())
1292 return false;
1293 }
1294
Douglas Gregor14f232e2010-05-08 23:05:03 +00001295 // If we failed to complete the type for some reason, or if the type is
1296 // dependent, don't diagnose the variable.
1297 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001298 return false;
1299
John McCallcef15822010-03-31 02:47:45 +00001300 if (const TagType *TT = Ty->getAs<TagType>()) {
1301 const TagDecl *Tag = TT->getDecl();
1302 if (Tag->hasAttr<UnusedAttr>())
1303 return false;
1304
1305 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001306 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001307 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001308
1309 if (const Expr *Init = VD->getInit()) {
David Blaikiea9d4a932012-10-24 21:29:06 +00001310 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1311 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001312 const CXXConstructExpr *Construct =
1313 dyn_cast<CXXConstructExpr>(Init);
1314 if (Construct && !Construct->isElidable()) {
1315 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001316 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001317 return false;
1318 }
1319 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001320 }
1321 }
John McCallcef15822010-03-31 02:47:45 +00001322
1323 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001324 }
1325
John McCall67da35c2010-02-04 22:26:26 +00001326 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001327}
1328
Anna Zaks964f4c62011-07-28 20:52:06 +00001329static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1330 FixItHint &Hint) {
1331 if (isa<LabelDecl>(D)) {
1332 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001333 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001334 if (AfterColon.isInvalid())
1335 return;
1336 Hint = FixItHint::CreateRemoval(CharSourceRange::
1337 getCharRange(D->getLocStart(), AfterColon));
1338 }
1339 return;
1340}
1341
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001342/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1343/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001344void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001345 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001346 if (!ShouldDiagnoseUnusedDecl(D))
1347 return;
1348
Anna Zaks964f4c62011-07-28 20:52:06 +00001349 GenerateFixForUnusedDecl(D, Context, Hint);
1350
Chris Lattnercab02a62011-02-17 20:34:02 +00001351 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001352 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001353 DiagID = diag::warn_unused_exception_param;
1354 else if (isa<LabelDecl>(D))
1355 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001356 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001357 DiagID = diag::warn_unused_variable;
1358
Anna Zaks964f4c62011-07-28 20:52:06 +00001359 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001360}
1361
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001362static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1363 // Verify that we have no forward references left. If so, there was a goto
1364 // or address of a label taken, but no definition of it. Label fwd
1365 // definitions are indicated with a null substmt.
1366 if (L->getStmt() == 0)
1367 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1368}
1369
Steve Naroffc62adb62007-10-09 22:01:59 +00001370void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001371 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001372 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001373 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001374
Chris Lattner302b4be2006-11-19 02:31:38 +00001375 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1376 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001377 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001378 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001379
Douglas Gregor91f84212008-12-11 16:49:14 +00001380 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1381 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001382
Douglas Gregor91f84212008-12-11 16:49:14 +00001383 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001384
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001385 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001386 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001387 DiagnoseUnusedDecl(D);
1388
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001389 // If this was a forward reference to a label, verify it was defined.
1390 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1391 CheckPoppedLabel(LD, *this);
1392
Douglas Gregor91f84212008-12-11 16:49:14 +00001393 // Remove this name from our lexical scope.
1394 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001395 }
1396}
1397
James Molloy6f8780b2012-02-29 10:24:19 +00001398void Sema::ActOnStartFunctionDeclarator() {
1399 ++InFunctionDeclarator;
1400}
1401
1402void Sema::ActOnEndFunctionDeclarator() {
1403 assert(InFunctionDeclarator);
1404 --InFunctionDeclarator;
1405}
1406
Douglas Gregor1c283312010-08-11 12:19:30 +00001407/// \brief Look for an Objective-C class in the translation unit.
1408///
1409/// \param Id The name of the Objective-C class we're looking for. If
1410/// typo-correction fixes this name, the Id will be updated
1411/// to the fixed name.
1412///
1413/// \param IdLoc The location of the name in the translation unit.
1414///
James Dennett41725122012-06-22 10:16:05 +00001415/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001416/// if there is no class with the given name.
1417///
1418/// \returns The declaration of the named Objective-C class, or NULL if the
1419/// class could not be found.
1420ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1421 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001422 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001423 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1424 // creation from this context.
1425 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1426
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001427 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001428 // Perform typo correction at the given location, but only if we
1429 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001430 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1431 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1432 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001433 Validator)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001434 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001435 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001436 Id = IDecl->getIdentifier();
1437 }
1438 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001439 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1440 // This routine must always return a class definition, if any.
1441 if (Def && Def->getDefinition())
1442 Def = Def->getDefinition();
1443 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001444}
1445
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001446/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1447/// from S, where a non-field would be declared. This routine copes
1448/// with the difference between C and C++ scoping rules in structs and
1449/// unions. For example, the following code is well-formed in C but
1450/// ill-formed in C++:
1451/// @code
1452/// struct S6 {
1453/// enum { BAR } e;
1454/// };
Mike Stump11289f42009-09-09 15:08:12 +00001455///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001456/// void test_S6() {
1457/// struct S6 a;
1458/// a.e = BAR;
1459/// }
1460/// @endcode
1461/// For the declaration of BAR, this routine will return a different
1462/// scope. The scope S will be the scope of the unnamed enumeration
1463/// within S6. In C++, this routine will return the scope associated
1464/// with S6, because the enumeration's scope is a transparent
1465/// context but structures can contain non-field names. In C, this
1466/// routine will return the translation unit scope, since the
1467/// enumeration's scope is a transparent context and structures cannot
1468/// contain non-field names.
1469Scope *Sema::getNonFieldDeclScope(Scope *S) {
1470 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001471 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001472 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001473 S = S->getParent();
1474 return S;
1475}
1476
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001477/// \brief Looks up the declaration of "struct objc_super" and
1478/// saves it for later use in building builtin declaration of
1479/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1480/// pre-existing declaration exists no action takes place.
1481static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1482 IdentifierInfo *II) {
1483 if (!II->isStr("objc_msgSendSuper"))
1484 return;
1485 ASTContext &Context = ThisSema.Context;
1486
1487 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1488 SourceLocation(), Sema::LookupTagName);
1489 ThisSema.LookupName(Result, S);
1490 if (Result.getResultKind() == LookupResult::Found)
1491 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1492 Context.setObjCSuperType(Context.getTagDeclType(TD));
1493}
1494
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001495/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1496/// file scope. lazily create a decl for it. ForRedeclaration is true
1497/// if we're creating this built-in in anticipation of redeclaring the
1498/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001499NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001500 Scope *S, bool ForRedeclaration,
1501 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001502 LookupPredefedObjCSuperType(*this, S, II);
1503
Chris Lattner9561a0b2007-01-28 08:20:04 +00001504 Builtin::ID BID = (Builtin::ID)bid;
1505
Chris Lattnerecd79c62009-06-14 00:45:47 +00001506 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001507 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001508 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001509 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001510 // Okay
1511 break;
1512
Mike Stump93246cc2009-07-28 23:57:15 +00001513 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001514 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001515 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001516 << Context.BuiltinInfo.GetName(BID);
1517 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001518
Mike Stump93246cc2009-07-28 23:57:15 +00001519 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001520 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001521 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001522 << Context.BuiltinInfo.GetName(BID);
1523 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001524
1525 case ASTContext::GE_Missing_ucontext:
1526 if (ForRedeclaration)
1527 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1528 << Context.BuiltinInfo.GetName(BID);
1529 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001530 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001531
1532 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1533 Diag(Loc, diag::ext_implicit_lib_function_decl)
1534 << Context.BuiltinInfo.GetName(BID)
1535 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001536 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001537 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001538 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001539 Diag(Loc, diag::note_please_include_header)
1540 << Context.BuiltinInfo.getHeaderName(BID)
1541 << Context.BuiltinInfo.GetName(BID);
1542 }
1543
Warren Hunt445d83e2013-11-01 23:46:51 +00001544 DeclContext *Parent = Context.getTranslationUnitDecl();
1545 if (getLangOpts().CPlusPlus) {
1546 LinkageSpecDecl *CLinkageDecl =
1547 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1548 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001549 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001550 Parent->addDecl(CLinkageDecl);
1551 Parent = CLinkageDecl;
1552 }
1553
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001554 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001555 Parent,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001556 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001557 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001558 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001559 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001560 New->setImplicit();
1561
Chris Lattner4dd27102008-05-05 22:18:14 +00001562 // Create Decl objects for each parameter, adding them to the
1563 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001564 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001565 SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001566 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1567 ParmVarDecl *parm =
1568 ParmVarDecl::Create(Context, New, SourceLocation(),
1569 SourceLocation(), 0,
1570 FT->getArgType(i), /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001571 SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001572 parm->setScopeInfo(0, i);
1573 Params.push_back(parm);
1574 }
David Blaikie9c70e042011-09-21 18:16:56 +00001575 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001576 }
Mike Stump11289f42009-09-09 15:08:12 +00001577
1578 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001579 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001580
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001581 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001582 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1583 // relate Scopes to DeclContexts, and probably eliminate CurContext
1584 // entirely, but we're not there yet.
1585 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001586 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001587 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001588 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001589 return New;
1590}
1591
Douglas Gregor3552dab2013-01-09 00:47:56 +00001592/// \brief Filter out any previous declarations that the given declaration
1593/// should not consider because they are not permitted to conflict, e.g.,
1594/// because they come from hidden sub-modules and do not refer to the same
1595/// entity.
1596static void filterNonConflictingPreviousDecls(ASTContext &context,
1597 NamedDecl *decl,
1598 LookupResult &previous){
1599 // This is only interesting when modules are enabled.
1600 if (!context.getLangOpts().Modules)
1601 return;
1602
1603 // Empty sets are uninteresting.
1604 if (previous.empty())
1605 return;
1606
Douglas Gregor3552dab2013-01-09 00:47:56 +00001607 LookupResult::Filter filter = previous.makeFilter();
1608 while (filter.hasNext()) {
1609 NamedDecl *old = filter.next();
1610
1611 // Non-hidden declarations are never ignored.
1612 if (!old->isHidden())
1613 continue;
1614
Rafael Espindola3ae00052013-05-13 00:12:11 +00001615 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001616 filter.erase();
1617 }
1618
1619 filter.done();
1620}
1621
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001622bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1623 QualType OldType;
1624 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1625 OldType = OldTypedef->getUnderlyingType();
1626 else
1627 OldType = Context.getTypeDeclType(Old);
1628 QualType NewType = New->getUnderlyingType();
1629
Douglas Gregoraab36982012-01-11 22:33:48 +00001630 if (NewType->isVariablyModifiedType()) {
1631 // Must not redefine a typedef with a variably-modified type.
1632 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1633 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1634 << Kind << NewType;
1635 if (Old->getLocation().isValid())
1636 Diag(Old->getLocation(), diag::note_previous_definition);
1637 New->setInvalidDecl();
1638 return true;
1639 }
1640
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001641 if (OldType != NewType &&
1642 !OldType->isDependentType() &&
1643 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001644 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001645 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1646 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1647 << Kind << NewType << OldType;
1648 if (Old->getLocation().isValid())
1649 Diag(Old->getLocation(), diag::note_previous_definition);
1650 New->setInvalidDecl();
1651 return true;
1652 }
1653 return false;
1654}
1655
Richard Smithdda56e42011-04-15 14:24:37 +00001656/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001657/// same name and scope as a previous declaration 'Old'. Figure out
1658/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001659/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001660///
Richard Smithdda56e42011-04-15 14:24:37 +00001661void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001662 // If the new decl is known invalid already, don't bother doing any
1663 // merging checks.
1664 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001665
Steve Naroff44cfcb62008-09-09 14:32:20 +00001666 // Allow multiple definitions for ObjC built-in typedefs.
1667 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001668 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001669 const IdentifierInfo *TypeID = New->getIdentifier();
1670 switch (TypeID->getLength()) {
1671 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001672 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001673 {
1674 if (!TypeID->isStr("id"))
1675 break;
1676 QualType T = New->getUnderlyingType();
1677 if (!T->isPointerType())
1678 break;
1679 if (!T->isVoidPointerType()) {
1680 QualType PT = T->getAs<PointerType>()->getPointeeType();
1681 if (!PT->isStructureType())
1682 break;
1683 }
1684 Context.setObjCIdRedefinitionType(T);
1685 // Install the built-in type for 'id', ignoring the current definition.
1686 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1687 return;
1688 }
Chris Lattner66e32812008-11-20 05:41:43 +00001689 case 5:
1690 if (!TypeID->isStr("Class"))
1691 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001692 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001693 // Install the built-in type for 'Class', ignoring the current definition.
1694 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001695 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001696 case 3:
1697 if (!TypeID->isStr("SEL"))
1698 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001699 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001700 // Install the built-in type for 'SEL', ignoring the current definition.
1701 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001702 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001703 }
1704 // Fall through - the typedef name was not a builtin type.
1705 }
John McCall1f82f242009-11-18 22:49:29 +00001706
Douglas Gregorfb034662009-01-28 17:15:10 +00001707 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001708 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1709 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001710 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001711 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001712
1713 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001714 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001715 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001716
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001717 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001718 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001719
John McCall1f82f242009-11-18 22:49:29 +00001720 // If the old declaration is invalid, just give up here.
1721 if (Old->isInvalidDecl())
1722 return New->setInvalidDecl();
1723
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001724 // If the typedef types are not identical, reject them in all languages and
1725 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001726 if (isIncompatibleTypedef(Old, New))
1727 return;
Mike Stump11289f42009-09-09 15:08:12 +00001728
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001729 // The types match. Link up the redeclaration chain and merge attributes if
1730 // the old declaration was a typedef.
1731 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001732 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001733 mergeDeclAttributes(New, Old);
1734 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001735
David Blaikiebbafb8a2012-03-11 07:00:24 +00001736 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001737 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001738
David Blaikiebbafb8a2012-03-11 07:00:24 +00001739 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001740 // C++ [dcl.typedef]p2:
1741 // In a given non-class scope, a typedef specifier can be used to
1742 // redefine the name of any type declared in that scope to refer
1743 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001744 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001745 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001746
1747 // C++0x [dcl.typedef]p4:
1748 // In a given class scope, a typedef specifier can be used to redefine
1749 // any class-name declared in that scope that is not also a typedef-name
1750 // to refer to the type to which it already refers.
1751 //
1752 // This wording came in via DR424, which was a correction to the
1753 // wording in DR56, which accidentally banned code like:
1754 //
1755 // struct S {
1756 // typedef struct A { } A;
1757 // };
1758 //
1759 // in the C++03 standard. We implement the C++0x semantics, which
1760 // allow the above but disallow
1761 //
1762 // struct S {
1763 // typedef int I;
1764 // typedef int I;
1765 // };
1766 //
1767 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001768 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001769 return;
1770
Chris Lattner2581fc32009-04-17 22:04:20 +00001771 Diag(New->getLocation(), diag::err_redefinition)
1772 << New->getDeclName();
1773 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001774 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001775 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001776
Douglas Gregor7363fb02012-01-11 04:25:01 +00001777 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001778 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001779 return;
1780
Chris Lattner2581fc32009-04-17 22:04:20 +00001781 // If we have a redefinition of a typedef in C, emit a warning. This warning
1782 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001783 // -Wtypedef-redefinition. If either the original or the redefinition is
1784 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001785 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001786 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1787 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001788 return;
Mike Stump11289f42009-09-09 15:08:12 +00001789
Chris Lattner2581fc32009-04-17 22:04:20 +00001790 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1791 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001792 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001793 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001794}
1795
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001796/// DeclhasAttr - returns true if decl Declaration already has the target
1797/// attribute.
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001798static bool DeclHasAttr(const Decl *D, const Attr *A) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001799 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001800 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001801 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1802 if ((*i)->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001803 if (Ann) {
1804 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1805 return true;
1806 continue;
1807 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001808 // FIXME: Don't hardcode this check
1809 if (OA && isa<OwnershipAttr>(*i))
1810 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001811 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001812 }
Chris Lattner84966392008-03-03 03:28:21 +00001813
1814 return false;
1815}
1816
Richard Smithbc8caaf2013-02-22 04:55:39 +00001817static bool isAttributeTargetADefinition(Decl *D) {
1818 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1819 return VD->isThisDeclarationADefinition();
1820 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1821 return TD->isCompleteDefinition() || TD->isBeingDefined();
1822 return true;
1823}
1824
1825/// Merge alignment attributes from \p Old to \p New, taking into account the
1826/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1827///
1828/// \return \c true if any attributes were added to \p New.
1829static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1830 // Look for alignas attributes on Old, and pick out whichever attribute
1831 // specifies the strictest alignment requirement.
1832 AlignedAttr *OldAlignasAttr = 0;
1833 AlignedAttr *OldStrictestAlignAttr = 0;
1834 unsigned OldAlign = 0;
1835 for (specific_attr_iterator<AlignedAttr>
1836 I = Old->specific_attr_begin<AlignedAttr>(),
1837 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1838 // FIXME: We have no way of representing inherited dependent alignments
1839 // in a case like:
1840 // template<int A, int B> struct alignas(A) X;
1841 // template<int A, int B> struct alignas(B) X {};
1842 // For now, we just ignore any alignas attributes which are not on the
1843 // definition in such a case.
1844 if (I->isAlignmentDependent())
1845 return false;
1846
1847 if (I->isAlignas())
1848 OldAlignasAttr = *I;
1849
1850 unsigned Align = I->getAlignment(S.Context);
1851 if (Align > OldAlign) {
1852 OldAlign = Align;
1853 OldStrictestAlignAttr = *I;
1854 }
1855 }
1856
1857 // Look for alignas attributes on New.
1858 AlignedAttr *NewAlignasAttr = 0;
1859 unsigned NewAlign = 0;
1860 for (specific_attr_iterator<AlignedAttr>
1861 I = New->specific_attr_begin<AlignedAttr>(),
1862 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1863 if (I->isAlignmentDependent())
1864 return false;
1865
1866 if (I->isAlignas())
1867 NewAlignasAttr = *I;
1868
1869 unsigned Align = I->getAlignment(S.Context);
1870 if (Align > NewAlign)
1871 NewAlign = Align;
1872 }
1873
1874 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1875 // Both declarations have 'alignas' attributes. We require them to match.
1876 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1877 // fall short. (If two declarations both have alignas, they must both match
1878 // every definition, and so must match each other if there is a definition.)
1879
1880 // If either declaration only contains 'alignas(0)' specifiers, then it
1881 // specifies the natural alignment for the type.
1882 if (OldAlign == 0 || NewAlign == 0) {
1883 QualType Ty;
1884 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1885 Ty = VD->getType();
1886 else
1887 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1888
1889 if (OldAlign == 0)
1890 OldAlign = S.Context.getTypeAlign(Ty);
1891 if (NewAlign == 0)
1892 NewAlign = S.Context.getTypeAlign(Ty);
1893 }
1894
1895 if (OldAlign != NewAlign) {
1896 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1897 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1898 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1899 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1900 }
1901 }
1902
1903 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1904 // C++11 [dcl.align]p6:
1905 // if any declaration of an entity has an alignment-specifier,
1906 // every defining declaration of that entity shall specify an
1907 // equivalent alignment.
1908 // C11 6.7.5/7:
1909 // If the definition of an object does not have an alignment
1910 // specifier, any other declaration of that object shall also
1911 // have no alignment specifier.
1912 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001913 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001914 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001915 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001916 }
1917
1918 bool AnyAdded = false;
1919
1920 // Ensure we have an attribute representing the strictest alignment.
1921 if (OldAlign > NewAlign) {
1922 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1923 Clone->setInherited(true);
1924 New->addAttr(Clone);
1925 AnyAdded = true;
1926 }
1927
1928 // Ensure we have an alignas attribute if the old declaration had one.
1929 if (OldAlignasAttr && !NewAlignasAttr &&
1930 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1931 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1932 Clone->setInherited(true);
1933 New->addAttr(Clone);
1934 AnyAdded = true;
1935 }
1936
1937 return AnyAdded;
1938}
1939
1940static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1941 bool Override) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001942 InheritableAttr *NewAttr = NULL;
Michael Han99315932013-01-24 16:46:58 +00001943 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola19de5612013-01-12 06:42:30 +00001944 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001945 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1946 AA->getIntroduced(), AA->getDeprecated(),
1947 AA->getObsoleted(), AA->getUnavailable(),
1948 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001949 AttrSpellingListIndex);
Richard Smithbc8caaf2013-02-22 04:55:39 +00001950 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1951 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1952 AttrSpellingListIndex);
1953 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1954 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1955 AttrSpellingListIndex);
Rafael Espindola19de5612013-01-12 06:42:30 +00001956 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001957 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1958 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001959 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001960 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1961 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001962 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001963 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1964 FA->getFormatIdx(), FA->getFirstArg(),
1965 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001966 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001967 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1968 AttrSpellingListIndex);
1969 else if (isa<AlignedAttr>(Attr))
1970 // AlignedAttrs are handled separately, because we need to handle all
1971 // such attributes on a declaration at the same time.
1972 NewAttr = 0;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001973 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001974 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001975
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001976 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001977 NewAttr->setInherited(true);
1978 D->addAttr(NewAttr);
1979 return true;
1980 }
1981
1982 return false;
1983}
1984
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001985static const Decl *getDefinition(const Decl *D) {
1986 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00001987 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001988 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1989 const VarDecl *Def = VD->getDefinition();
1990 if (Def)
1991 return Def;
1992 return VD->getActingDefinition();
1993 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001994 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00001995 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001996 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00001997 return Def;
1998 }
1999 return NULL;
2000}
2001
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002002static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2003 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2004 I != E; ++I) {
2005 Attr *Attribute = *I;
2006 if (Attribute->getKind() == Kind)
2007 return true;
2008 }
2009 return false;
2010}
2011
2012/// checkNewAttributesAfterDef - If we already have a definition, check that
2013/// there are no new attributes in this declaration.
2014static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2015 if (!New->hasAttrs())
2016 return;
2017
2018 const Decl *Def = getDefinition(Old);
2019 if (!Def || Def == New)
2020 return;
2021
2022 AttrVec &NewAttributes = New->getAttrs();
2023 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2024 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002025
2026 if (isa<AliasAttr>(NewAttribute)) {
2027 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2028 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2029 else {
2030 VarDecl *VD = cast<VarDecl>(New);
2031 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2032 VarDecl::TentativeDefinition
2033 ? diag::err_alias_after_tentative
2034 : diag::err_redefinition;
2035 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2036 S.Diag(Def->getLocation(), diag::note_previous_definition);
2037 VD->setInvalidDecl();
2038 }
2039 ++I;
2040 continue;
2041 }
2042
2043 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2044 // Tentative definitions are only interesting for the alias check above.
2045 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2046 ++I;
2047 continue;
2048 }
2049 }
2050
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002051 if (hasAttribute(Def, NewAttribute->getKind())) {
2052 ++I;
2053 continue; // regular attr merging will take care of validating this.
2054 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002055
Richard Smithdebc59d2013-01-30 05:45:05 +00002056 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002057 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002058 ++I;
2059 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002060 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2061 if (AA->isAlignas()) {
2062 // C++11 [dcl.align]p6:
2063 // if any declaration of an entity has an alignment-specifier,
2064 // every defining declaration of that entity shall specify an
2065 // equivalent alignment.
2066 // C11 6.7.5/7:
2067 // If the definition of an object does not have an alignment
2068 // specifier, any other declaration of that object shall also
2069 // have no alignment specifier.
2070 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002071 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002072 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002073 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002074 NewAttributes.erase(NewAttributes.begin() + I);
2075 --E;
2076 continue;
2077 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002078 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002079
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002080 S.Diag(NewAttribute->getLocation(),
2081 diag::warn_attribute_precede_definition);
2082 S.Diag(Def->getLocation(), diag::note_previous_definition);
2083 NewAttributes.erase(NewAttributes.begin() + I);
2084 --E;
2085 }
2086}
2087
John McCallf79e87d2011-03-02 04:00:57 +00002088/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002089void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002090 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002091 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2092 UsedAttr *NewAttr = OldAttr->clone(Context);
2093 NewAttr->setInherited(true);
2094 New->addAttr(NewAttr);
2095 }
2096
Richard Smithe233fbf2013-01-28 22:42:45 +00002097 if (!Old->hasAttrs() && !New->hasAttrs())
2098 return;
2099
Rafael Espindola36191042012-05-18 01:47:00 +00002100 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002101 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002102
Douglas Gregor32c17572012-01-01 20:30:41 +00002103 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002104 return;
John McCallf79e87d2011-03-02 04:00:57 +00002105
Douglas Gregor32c17572012-01-01 20:30:41 +00002106 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002107
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002108 // Ensure that any moving of objects within the allocated map is done before
2109 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002110 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002111
Peter Collingbourneab8bc062011-01-21 02:08:36 +00002112 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor32c17572012-01-01 20:30:41 +00002113 i = Old->specific_attr_begin<InheritableAttr>(),
2114 e = Old->specific_attr_end<InheritableAttr>();
2115 i != e; ++i) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002116 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002117 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002118 if (isa<DeprecatedAttr>(*i) ||
2119 isa<UnavailableAttr>(*i) ||
2120 isa<AvailabilityAttr>(*i)) {
2121 switch (AMK) {
2122 case AMK_None:
2123 continue;
John McCalld2930c22011-07-22 02:45:48 +00002124
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002125 case AMK_Redeclaration:
2126 break;
2127
2128 case AMK_Override:
2129 Override = true;
2130 break;
2131 }
2132 }
2133
Rafael Espindolab0938852013-10-25 01:28:12 +00002134 // Already handled.
2135 if (isa<UsedAttr>(*i))
2136 continue;
2137
Richard Smithbc8caaf2013-02-22 04:55:39 +00002138 if (mergeDeclAttribute(*this, New, *i, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002139 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002140 }
John McCallf79e87d2011-03-02 04:00:57 +00002141
Richard Smithbc8caaf2013-02-22 04:55:39 +00002142 if (mergeAlignedAttrs(*this, New, Old))
2143 foundAny = true;
2144
Douglas Gregor32c17572012-01-01 20:30:41 +00002145 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002146}
2147
2148/// mergeParamDeclAttributes - Copy attributes from the old parameter
2149/// to the new one.
2150static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2151 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002152 Sema &S) {
2153 // C++11 [dcl.attr.depend]p2:
2154 // The first declaration of a function shall specify the
2155 // carries_dependency attribute for its declarator-id if any declaration
2156 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002157 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2158 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2159 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002160 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2161 // Find the first declaration of the parameter.
2162 // FIXME: Should we build redeclaration chains for function parameters?
2163 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002164 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002165 const ParmVarDecl *FirstVD =
2166 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2167 S.Diag(FirstVD->getLocation(),
2168 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2169 }
2170
John McCallf79e87d2011-03-02 04:00:57 +00002171 if (!oldDecl->hasAttrs())
2172 return;
2173
2174 bool foundAny = newDecl->hasAttrs();
2175
2176 // Ensure that any moving of objects within the allocated map is
2177 // done before we process them.
2178 if (!foundAny) newDecl->setAttrs(AttrVec());
2179
2180 for (specific_attr_iterator<InheritableParamAttr>
2181 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2182 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2183 if (!DeclHasAttr(newDecl, *i)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002184 InheritableAttr *newAttr =
2185 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002186 newAttr->setInherited(true);
2187 newDecl->addAttr(newAttr);
2188 foundAny = true;
2189 }
2190 }
2191
2192 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002193}
2194
Dan Gohman28ade552010-07-26 21:25:24 +00002195namespace {
2196
Douglas Gregora74a2972009-03-06 22:43:54 +00002197/// Used in MergeFunctionDecl to keep track of function parameters in
2198/// C.
2199struct GNUCompatibleParamWarning {
2200 ParmVarDecl *OldParm;
2201 ParmVarDecl *NewParm;
2202 QualType PromotedType;
2203};
2204
Dan Gohman28ade552010-07-26 21:25:24 +00002205}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002206
2207/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002208Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002209 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002210 if (Ctor->isDefaultConstructor())
2211 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002212
2213 if (Ctor->isCopyConstructor())
2214 return Sema::CXXCopyConstructor;
2215
2216 if (Ctor->isMoveConstructor())
2217 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002218 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002219 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002220 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002221 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002222 } else if (MD->isMoveAssignmentOperator()) {
2223 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002224 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002225
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002226 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002227}
2228
Sebastian Redl243d9052010-06-09 21:17:41 +00002229/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002230/// only extern inline functions can be redefined, and even then only in
2231/// GNU89 mode.
2232static bool canRedefineFunction(const FunctionDecl *FD,
2233 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002234 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2235 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002236 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002237 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002238}
2239
Reid Kleckner78af0702013-08-27 23:08:25 +00002240const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2241 const AttributedType *AT = T->getAs<AttributedType>();
2242 while (AT && !AT->isCallingConv())
2243 AT = AT->getModifiedType()->getAs<AttributedType>();
2244 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002245}
2246
Benjamin Kramer3e350262013-02-15 12:30:38 +00002247template <typename T>
2248static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002249 const DeclContext *DC = Old->getDeclContext();
2250 if (DC->isRecord())
2251 return false;
2252
2253 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002254 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002255 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002256 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002257 return true;
2258 return false;
2259}
2260
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002261/// MergeFunctionDecl - We just parsed a function 'New' from
2262/// declarator D which has the same name and scope as a previous
2263/// declaration 'Old'. Figure out how to resolve this situation,
2264/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002265///
2266/// In C++, New and Old must be declarations that are not
2267/// overloaded. Use IsOverload to determine whether New and Old are
2268/// overloaded, and to select the Old declaration that New should be
2269/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002270///
2271/// Returns true if there was an error, false otherwise.
Richard Smith1c34fb72013-08-13 18:18:50 +00002272bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2273 bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002274 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002275 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002276 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002277 = dyn_cast<FunctionTemplateDecl>(OldD))
2278 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002279 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002280 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00002281 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002282 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002283 if (New->getFriendObjectKind()) {
2284 Diag(New->getLocation(), diag::err_using_decl_friend);
2285 Diag(Shadow->getTargetDecl()->getLocation(),
2286 diag::note_using_decl_target);
2287 Diag(Shadow->getUsingDecl()->getLocation(),
2288 diag::note_using_decl) << 0;
2289 return true;
2290 }
2291
John McCalle29c5cd2009-12-10 19:51:03 +00002292 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2293 Diag(Shadow->getTargetDecl()->getLocation(),
2294 diag::note_using_decl_target);
2295 Diag(Shadow->getUsingDecl()->getLocation(),
2296 diag::note_using_decl) << 0;
2297 return true;
2298 }
2299
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002300 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002301 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002302 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002303 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00002304 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002305
David Majnemerea5092a2013-07-07 23:49:50 +00002306 // If the old declaration is invalid, just give up here.
2307 if (Old->isInvalidDecl())
2308 return true;
2309
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002310 // Determine whether the previous declaration was a definition,
2311 // implicit declaration, or a declaration.
2312 diag::kind PrevDiag;
2313 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002314 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002315 else if (Old->isImplicit())
2316 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002317 else
Chris Lattner0369c572008-11-23 23:12:31 +00002318 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002319
Charles Davisfea48452010-02-18 02:00:42 +00002320 // Don't complain about this if we're in GNU89 mode and the old function
2321 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002322 // Don't complain about specializations. They are not supposed to have
2323 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002324 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002325 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002326 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002327 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002328 !canRedefineFunction(Old, getLangOpts())) {
2329 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002330 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2331 Diag(Old->getLocation(), PrevDiag);
2332 } else {
2333 Diag(New->getLocation(), diag::err_static_non_static) << New;
2334 Diag(Old->getLocation(), PrevDiag);
2335 return true;
2336 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002337 }
2338
Reid Kleckner78af0702013-08-27 23:08:25 +00002339
2340 // If a function is first declared with a calling convention, but is later
2341 // declared or defined without one, all following decls assume the calling
2342 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002343 //
John McCalla5f46fb2012-08-25 02:00:03 +00002344 // It's OK if a function is first declared without a calling convention,
2345 // but is later declared or defined with the default calling convention.
2346 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002347 // To test if either decl has an explicit calling convention, we look for
2348 // AttributedType sugar nodes on the type as written. If they are missing or
2349 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002350 //
2351 // Note also that we DO NOT return at this point, because we still have
2352 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002353 QualType OldQType = Context.getCanonicalType(Old->getType());
2354 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002355 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002356 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002357 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2358 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2359 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002360
Reid Kleckner78af0702013-08-27 23:08:25 +00002361 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002362 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002363 const FunctionType *FT =
2364 First->getType().getCanonicalType()->castAs<FunctionType>();
2365 FunctionType::ExtInfo FI = FT->getExtInfo();
2366 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2367 if (!NewCCExplicit) {
2368 // Inherit the CC from the previous declaration if it was specified
2369 // there but not here.
2370 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2371 RequiresAdjustment = true;
2372 } else {
2373 // Calling conventions aren't compatible, so complain.
2374 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2375 Diag(New->getLocation(), diag::err_cconv_change)
2376 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2377 << !FirstCCExplicit
2378 << (!FirstCCExplicit ? "" :
2379 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002380
Reid Kleckner78af0702013-08-27 23:08:25 +00002381 // Put the note on the first decl, since it is the one that matters.
2382 Diag(First->getLocation(), diag::note_previous_declaration);
2383 return true;
2384 }
John McCallcddbad02010-02-04 05:44:44 +00002385 }
2386
John McCallab26cfa2010-02-05 21:31:56 +00002387 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002388 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2389 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2390 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002391 }
2392
Douglas Gregor77e274f2010-06-18 21:30:25 +00002393 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002394 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2395 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2396 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002397 Diag(New->getLocation(), diag::err_regparm_mismatch)
2398 << NewType->getRegParmType()
2399 << OldType->getRegParmType();
2400 Diag(Old->getLocation(), diag::note_previous_declaration);
2401 return true;
2402 }
John McCall4f5019e2010-12-19 02:44:49 +00002403
2404 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2405 RequiresAdjustment = true;
2406 }
2407
Douglas Gregorf1404d72011-10-14 15:55:40 +00002408 // Merge ns_returns_retained attribute.
2409 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2410 if (NewTypeInfo.getProducesResult()) {
2411 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2412 Diag(Old->getLocation(), diag::note_previous_declaration);
2413 return true;
2414 }
2415
2416 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2417 RequiresAdjustment = true;
2418 }
2419
John McCall4f5019e2010-12-19 02:44:49 +00002420 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002421 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2422 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2423 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002424 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002425 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002426 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002427
2428 // If this redeclaration makes the function inline, we may need to add it to
2429 // UndefinedButUsed.
2430 if (!Old->isInlined() && New->isInlined() &&
2431 !New->hasAttr<GNUInlineAttr>() &&
2432 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2433 Old->isUsed(false) &&
2434 !Old->isDefined() && !New->isThisDeclarationADefinition())
2435 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2436 SourceLocation()));
2437
2438 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2439 // about it.
2440 if (New->hasAttr<GNUInlineAttr>() &&
2441 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2442 UndefinedButUsed.erase(Old->getCanonicalDecl());
2443 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002444
David Blaikiebbafb8a2012-03-11 07:00:24 +00002445 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002446 // (C++98 13.1p2):
2447 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002448 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002449 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002450
2451 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002452 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002453 // Redeclarations or specializations of a function or function template
2454 // with a declared return type that uses a placeholder type shall also
2455 // use that placeholder, not a deduced type.
2456 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2457 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2458 : OldType)->getResultType();
2459 QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2460 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2461 : NewType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002462 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002463 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2464 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2465 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002466 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2467 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002468 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2469 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002470 if (New->isCXXClassMember() && New->isOutOfLine())
2471 Diag(New->getLocation(),
2472 diag::err_member_def_does_not_match_ret_type) << New;
2473 else
2474 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002475 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2476 return true;
2477 }
2478 else
2479 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002480 }
2481
Richard Smith2a7d4812013-05-04 07:00:32 +00002482 QualType OldReturnType = OldType->getResultType();
2483 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2484 if (OldReturnType != NewReturnType) {
2485 // If this function has a deduced return type and has already been
2486 // defined, copy the deduced value from the old declaration.
2487 AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2488 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002489 New->setType(
2490 SubstAutoType(New->getType(),
2491 OldAT->isDependentType() ? Context.DependentTy
2492 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002493 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002494 SubstAutoType(NewQType,
2495 OldAT->isDependentType() ? Context.DependentTy
2496 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002497 }
2498 }
2499
2500 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2501 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002502 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002503 // Preserve triviality.
2504 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002505
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002506 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002507 // 2 CXXMethodDecls referring to the same function will be injected.
2508 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002509 bool IsClassScopeExplicitSpecialization =
2510 OldMethod->isFunctionTemplateSpecialization() &&
2511 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002512 bool isFriend = NewMethod->getFriendObjectKind();
2513
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002514 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2515 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002516 // -- Member function declarations with the same name and the
2517 // same parameter types cannot be overloaded if any of them
2518 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002519 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002520 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2521 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2522 return true;
2523 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002524
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002525 // C++ [class.mem]p1:
2526 // [...] A member shall not be declared twice in the
2527 // member-specification, except that a nested class or member
2528 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002529 if (ActiveTemplateInstantiations.empty()) {
2530 unsigned NewDiag;
2531 if (isa<CXXConstructorDecl>(OldMethod))
2532 NewDiag = diag::err_constructor_redeclared;
2533 else if (isa<CXXDestructorDecl>(NewMethod))
2534 NewDiag = diag::err_destructor_redeclared;
2535 else if (isa<CXXConversionDecl>(NewMethod))
2536 NewDiag = diag::err_conv_function_redeclared;
2537 else
2538 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002539
Richard Smith57e7ff92012-07-13 04:12:04 +00002540 Diag(New->getLocation(), NewDiag);
2541 } else {
2542 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2543 << New << New->getType();
2544 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002545 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002546
2547 // Complain if this is an explicit declaration of a special
2548 // member that was initially declared implicitly.
2549 //
2550 // As an exception, it's okay to befriend such methods in order
2551 // to permit the implicit constructor/destructor/operator calls.
2552 } else if (OldMethod->isImplicit()) {
2553 if (isFriend) {
2554 NewMethod->setImplicit();
2555 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002556 Diag(NewMethod->getLocation(),
2557 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002558 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002559 return true;
2560 }
Richard Smith337a5a12012-06-08 01:30:54 +00002561 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002562 Diag(NewMethod->getLocation(),
2563 diag::err_definition_of_explicitly_defaulted_member)
2564 << getSpecialMember(OldMethod);
2565 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002566 }
2567 }
2568
Richard Smith10876ef2013-01-17 01:30:42 +00002569 // C++11 [dcl.attr.noreturn]p1:
2570 // The first declaration of a function shall specify the noreturn
2571 // attribute if any declaration of that function specifies the noreturn
2572 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002573 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2574 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2575 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002576 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002577 diag::note_noreturn_missing_first_decl);
2578 }
2579
Richard Smithe233fbf2013-01-28 22:42:45 +00002580 // C++11 [dcl.attr.depend]p2:
2581 // The first declaration of a function shall specify the
2582 // carries_dependency attribute for its declarator-id if any declaration
2583 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002584 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2585 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2586 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002587 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002588 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002589 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2590 }
2591
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002592 // (C++98 8.3.5p3):
2593 // All declarations for a function shall agree exactly in both the
2594 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002595 // We also want to respect all the extended bits except noreturn.
2596
2597 // noreturn should now match unless the old type info didn't have it.
2598 QualType OldQTypeForComparison = OldQType;
2599 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2600 assert(OldQType == QualType(OldType, 0));
2601 const FunctionType *OldTypeForComparison
2602 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2603 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2604 assert(OldQTypeForComparison.isCanonical());
2605 }
2606
Rafael Espindolaf4187652013-02-14 01:18:37 +00002607 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002608 // As a special case, retain the language linkage from previous
2609 // declarations of a friend function as an extension.
2610 //
2611 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2612 // and is useful because there's otherwise no way to specify language
2613 // linkage within class scope.
2614 //
2615 // Check cautiously as the friend object kind isn't yet complete.
2616 if (New->getFriendObjectKind() != Decl::FOK_None) {
2617 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2618 Diag(Old->getLocation(), PrevDiag);
2619 } else {
2620 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2621 Diag(Old->getLocation(), PrevDiag);
2622 return true;
2623 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002624 }
2625
John McCall4f5019e2010-12-19 02:44:49 +00002626 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002627 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002628
Richard Smith541b38b2013-09-20 01:15:31 +00002629 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2630 New->isLocalExternDecl()) {
2631 // It's OK if we couldn't merge types for a local function declaraton
2632 // if either the old or new type is dependent. We'll merge the types
2633 // when we instantiate the function.
2634 return false;
2635 }
2636
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002637 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002638 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002639
2640 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002641 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002642 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002643 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002644 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2645 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002646 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002647 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002648 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002649 // The old declaration provided a function prototype, but the
2650 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002651 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002652 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002653 OldProto->arg_type_end());
2654 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002655 ParamTypes,
John McCalldb40c7f2010-12-14 08:05:40 +00002656 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002657 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002658 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002659
2660 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002661 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00002662 for (FunctionProtoType::arg_type_iterator
2663 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002664 ParamEnd = OldProto->arg_type_end();
2665 ParamType != ParamEnd; ++ParamType) {
2666 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002667 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002668 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002669 *ParamType, /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002670 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002671 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002672 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002673 Param->setImplicit();
2674 Params.push_back(Param);
2675 }
2676
David Blaikie9c70e042011-09-21 18:16:56 +00002677 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002678 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002679
Richard Smith1c34fb72013-08-13 18:18:50 +00002680 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002681 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002682
Douglas Gregora74a2972009-03-06 22:43:54 +00002683 // GNU C permits a K&R definition to follow a prototype declaration
2684 // if the declared types of the parameters in the K&R definition
2685 // match the types in the prototype declaration, even when the
2686 // promoted types of the parameters from the K&R definition differ
2687 // from the types in the prototype. GCC then keeps the types from
2688 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002689 //
2690 // If a variadic prototype is followed by a non-variadic K&R definition,
2691 // the K&R definition becomes variadic. This is sort of an edge case, but
2692 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2693 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002694 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002695 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002696 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002697 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002698 SmallVector<QualType, 16> ArgTypes;
2699 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002700 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002701 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002702 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002703 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002704
Douglas Gregora74a2972009-03-06 22:43:54 +00002705 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002706 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2707 NewProto->getResultType());
2708 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002709 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002710 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002711 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2712 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002713 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00002714 NewProto->getArgType(Idx))) {
2715 ArgTypes.push_back(NewParm->getType());
2716 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002717 NewParm->getType(),
2718 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00002719 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00002720 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2721 Warnings.push_back(Warn);
2722 ArgTypes.push_back(NewParm->getType());
2723 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002724 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002725 }
2726
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002727 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002728 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2729 Diag(Warnings[Warn].NewParm->getLocation(),
2730 diag::ext_param_promoted_not_compatible_with_prototype)
2731 << Warnings[Warn].PromotedType
2732 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002733 if (Warnings[Warn].OldParm->getLocation().isValid())
2734 Diag(Warnings[Warn].OldParm->getLocation(),
2735 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002736 }
2737
Richard Smith1c34fb72013-08-13 18:18:50 +00002738 if (MergeTypeWithOld)
2739 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2740 OldProto->getExtProtoInfo()));
2741 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002742 }
2743
2744 // Fall through to diagnose conflicting types.
2745 }
2746
John McCallad327cd2013-04-14 08:50:55 +00002747 // A function that has already been declared has been redeclared or
2748 // defined with a different type; show an appropriate diagnostic.
2749
2750 // If the previous declaration was an implicitly-generated builtin
2751 // declaration, then at the very least we should use a specialized note.
2752 unsigned BuiltinID;
2753 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2754 // If it's actually a library-defined builtin function like 'malloc'
2755 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002756 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002757 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2758 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2759 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002760
2761 // If this is a global redeclaration, just forget hereafter
2762 // about the "builtin-ness" of the function.
2763 //
2764 // Doing this for local extern declarations is problematic. If
2765 // the builtin declaration remains visible, a second invalid
2766 // local declaration will produce a hard error; if it doesn't
2767 // remain visible, a single bogus local redeclaration (which is
2768 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002769 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002770 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2771
Douglas Gregor893c2c92009-03-23 17:47:24 +00002772 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002773 }
Steve Naroff17832a42008-01-16 15:01:34 +00002774
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002775 PrevDiag = diag::note_previous_builtin_declaration;
2776 }
2777
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002778 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002779 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002780 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002781}
2782
Douglas Gregore62c0a42009-02-24 01:23:02 +00002783/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002784/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002785///
2786/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002787/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002788/// the new declaration, once we know that New is in fact a
2789/// redeclaration of Old.
2790///
2791/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002792bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002793 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002794 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002795 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002796
Douglas Gregore62c0a42009-02-24 01:23:02 +00002797 // Merge "pure" flag.
2798 if (Old->isPure())
2799 New->setPure();
2800
Rafael Espindolabefe1302012-11-25 14:07:59 +00002801 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002802 if (Old->getMostRecentDecl()->isUsed(false))
2803 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002804
John McCallf79e87d2011-03-02 04:00:57 +00002805 // Merge attributes from the parameters. These can mismatch with K&R
2806 // declarations.
2807 if (New->getNumParams() == Old->getNumParams())
2808 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2809 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002810 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002811
David Blaikiebbafb8a2012-03-11 07:00:24 +00002812 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002813 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002814
Rafael Espindola8778c282012-11-29 16:09:03 +00002815 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002816 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2817 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002818 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002819 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002820 New->setType(Merged);
2821
Douglas Gregore62c0a42009-02-24 01:23:02 +00002822 return false;
2823}
2824
John McCall31168b02011-06-15 23:02:42 +00002825
John McCallf79e87d2011-03-02 04:00:57 +00002826void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002827 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002828
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002829 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002830 AvailabilityMergeKind MergeKind =
2831 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2832 : AMK_Override;
2833 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002834
2835 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002836 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2837 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002838 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002839 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002840 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002841 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002842
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002843 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002844}
2845
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002846/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2847/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002848/// emitting diagnostics as appropriate.
2849///
2850/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002851/// to here in AddInitializerToDecl. We can't check them before the initializer
2852/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002853void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2854 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002855 if (New->isInvalidDecl() || Old->isInvalidDecl())
2856 return;
2857
2858 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002859 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002860 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002861 // We don't know what the new type is until the initializer is attached.
2862 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002863 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2864 // These could still be something that needs exception specs checked.
2865 return MergeVarDeclExceptionSpecs(New, Old);
2866 }
Richard Smith30482bc2011-02-20 03:19:35 +00002867 // C++ [basic.link]p10:
2868 // [...] the types specified by all declarations referring to a given
2869 // object or function shall be identical, except that declarations for an
2870 // array object can specify array types that differ by the presence or
2871 // absence of a major array bound (8.3.4).
2872 else if (Old->getType()->isIncompleteArrayType() &&
2873 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002874 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2875 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2876 if (Context.hasSameType(OldArray->getElementType(),
2877 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002878 MergedT = New->getType();
2879 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002880 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002881 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2882 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2883 if (Context.hasSameType(OldArray->getElementType(),
2884 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002885 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002886 } else if (New->getType()->isObjCObjectPointerType() &&
2887 Old->getType()->isObjCObjectPointerType()) {
2888 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2889 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002890 }
2891 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002892 // C 6.2.7p2:
2893 // All declarations that refer to the same object or function shall have
2894 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002895 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2896 }
2897 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002898 // It's OK if we couldn't merge types if either type is dependent, for a
2899 // block-scope variable. In other cases (static data members of class
2900 // templates, variable templates, ...), we require the types to be
2901 // equivalent.
2902 // FIXME: The C++ standard doesn't say anything about this.
2903 if ((New->getType()->isDependentType() ||
2904 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2905 // If the old type was dependent, we can't merge with it, so the new type
2906 // becomes dependent for now. We'll reproduce the original type when we
2907 // instantiate the TypeSourceInfo for the variable.
2908 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2909 New->setType(Context.DependentTy);
2910 return;
2911 }
2912
2913 // FIXME: Even if this merging succeeds, some other non-visible declaration
2914 // of this variable might have an incompatible type. For instance:
2915 //
2916 // extern int arr[];
2917 // void f() { extern int arr[2]; }
2918 // void g() { extern int arr[3]; }
2919 //
2920 // Neither C nor C++ requires a diagnostic for this, but we should still try
2921 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002922 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002923 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002924 Diag(Old->getLocation(), diag::note_previous_definition);
2925 return New->setInvalidDecl();
2926 }
John McCallb65e8fe2013-04-01 18:34:28 +00002927
2928 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002929 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002930 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002931 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002932}
2933
Richard Smith3c785782013-09-03 21:00:58 +00002934static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2935 LookupResult &Previous) {
2936 // C11 6.2.7p4:
2937 // For an identifier with internal or external linkage declared
2938 // in a scope in which a prior declaration of that identifier is
2939 // visible, if the prior declaration specifies internal or
2940 // external linkage, the type of the identifier at the later
2941 // declaration becomes the composite type.
2942 //
2943 // If the variable isn't visible, we do not merge with its type.
2944 if (Previous.isShadowed())
2945 return false;
2946
2947 if (S.getLangOpts().CPlusPlus) {
2948 // C++11 [dcl.array]p3:
2949 // If there is a preceding declaration of the entity in the same
2950 // scope in which the bound was specified, an omitted array bound
2951 // is taken to be the same as in that earlier declaration.
2952 return NewVD->isPreviousDeclInSameBlockScope() ||
2953 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2954 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2955 } else {
2956 // If the old declaration was function-local, don't merge with its
2957 // type unless we're in the same function.
2958 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2959 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2960 }
2961}
2962
Chris Lattner01564d92007-01-27 19:27:06 +00002963/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2964/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2965/// situation, merging decls or emitting diagnostics as appropriate.
2966///
Mike Stump11289f42009-09-09 15:08:12 +00002967/// Tentative definition rules (C99 6.9.2p2) are checked by
2968/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002969/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002970///
Richard Smith3c785782013-09-03 21:00:58 +00002971void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00002972 // If the new decl is already invalid, don't do any other checking.
2973 if (New->isInvalidDecl())
2974 return;
Mike Stump11289f42009-09-09 15:08:12 +00002975
Richard Smithbeef3452014-01-16 23:39:20 +00002976 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2977
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002978 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00002979 VarDecl *Old = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00002980 VarTemplateDecl *OldTemplate = 0;
2981 if (Previous.isSingleResult()) {
2982 if (NewTemplate) {
2983 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2984 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
2985 } else
2986 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002987 }
2988 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002989 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002990 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002991 Diag(Previous.getRepresentativeDecl()->getLocation(),
2992 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002993 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002994 }
Chris Lattner84966392008-03-03 03:28:21 +00002995
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00002996 if (!shouldLinkPossiblyHiddenDecl(Old, New))
2997 return;
2998
Richard Smithbeef3452014-01-16 23:39:20 +00002999 // Ensure the template parameters are compatible.
3000 if (NewTemplate &&
3001 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3002 OldTemplate->getTemplateParameters(),
3003 /*Complain=*/true, TPL_TemplateMatch))
3004 return;
3005
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003006 // C++ [class.mem]p1:
3007 // A member shall not be declared twice in the member-specification [...]
3008 //
3009 // Here, we need only consider static data members.
3010 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3011 Diag(New->getLocation(), diag::err_duplicate_member)
3012 << New->getIdentifier();
3013 Diag(Old->getLocation(), diag::note_previous_declaration);
3014 New->setInvalidDecl();
3015 }
3016
Douglas Gregor32c17572012-01-01 20:30:41 +00003017 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003018 // Warn if an already-declared variable is made a weak_import in a subsequent
3019 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003020 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003021 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003022 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003023 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3024 Diag(Old->getLocation(), diag::note_previous_definition);
3025 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003026 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003027 }
Chris Lattner84966392008-03-03 03:28:21 +00003028
Richard Smith30482bc2011-02-20 03:19:35 +00003029 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003030 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3031
Richard Smith30482bc2011-02-20 03:19:35 +00003032 if (New->isInvalidDecl())
3033 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003034
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003035 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003036 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003037 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003038 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003039 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003040 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003041 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003042 }
Mike Stump11289f42009-09-09 15:08:12 +00003043 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003044 // For an identifier declared with the storage-class specifier
3045 // extern in a scope in which a prior declaration of that
3046 // identifier is visible,23) if the prior declaration specifies
3047 // internal or external linkage, the linkage of the identifier at
3048 // the later declaration is the same as the linkage specified at
3049 // the prior declaration. If no prior declaration is visible, or
3050 // if the prior declaration specifies no linkage, then the
3051 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003052 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003053 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003054 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003055 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003056 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003057 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003058 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003059 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003060 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003061
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003062 // Check if extern is followed by non-extern and vice-versa.
3063 if (New->hasExternalStorage() &&
3064 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3065 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3066 Diag(Old->getLocation(), diag::note_previous_definition);
3067 return New->setInvalidDecl();
3068 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003069 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3070 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003071 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3072 Diag(Old->getLocation(), diag::note_previous_definition);
3073 return New->setInvalidDecl();
3074 }
3075
Steve Naroffa5629372008-09-17 14:05:40 +00003076 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003077
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003078 // FIXME: The test for external storage here seems wrong? We still
3079 // need to check for mismatches.
3080 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003081 // Don't complain about out-of-line definitions of static members.
3082 !(Old->getLexicalDeclContext()->isRecord() &&
3083 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003084 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003085 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003086 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003087 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003088
Richard Smithfd3834f2013-04-13 02:43:54 +00003089 if (New->getTLSKind() != Old->getTLSKind()) {
3090 if (!Old->getTLSKind()) {
3091 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3092 Diag(Old->getLocation(), diag::note_previous_declaration);
3093 } else if (!New->getTLSKind()) {
3094 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3095 Diag(Old->getLocation(), diag::note_previous_declaration);
3096 } else {
3097 // Do not allow redeclaration to change the variable between requiring
3098 // static and dynamic initialization.
3099 // FIXME: GCC allows this, but uses the TLS keyword on the first
3100 // declaration to determine the kind. Do we need to be compatible here?
3101 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3102 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3103 Diag(Old->getLocation(), diag::note_previous_declaration);
3104 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003105 }
3106
Sebastian Redlf1842912010-02-02 18:35:11 +00003107 // C++ doesn't have tentative definitions, so go right ahead and check here.
3108 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003109 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003110 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003111 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003112 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003113 Diag(Def->getLocation(), diag::note_previous_definition);
3114 New->setInvalidDecl();
3115 return;
3116 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003117
Rafael Espindolaf4187652013-02-14 01:18:37 +00003118 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003119 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3120 Diag(Old->getLocation(), diag::note_previous_definition);
3121 New->setInvalidDecl();
3122 return;
3123 }
3124
Rafael Espindolabefe1302012-11-25 14:07:59 +00003125 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003126 if (Old->getMostRecentDecl()->isUsed(false))
3127 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003128
Douglas Gregor0760fa12009-03-10 23:43:53 +00003129 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003130 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003131 if (NewTemplate)
3132 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003133
3134 // Inherit access appropriately.
3135 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003136 if (NewTemplate)
3137 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003138}
3139
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003140/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3141/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003142Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003143 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003144 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003145}
3146
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003147static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003148 if (!S.Context.getLangOpts().CPlusPlus)
3149 return;
3150
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003151 if (isa<CXXRecordDecl>(Tag->getParent())) {
3152 // If this tag is the direct child of a class, number it if
3153 // it is anonymous.
3154 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3155 return;
3156 MangleNumberingContext &MCtx =
3157 S.Context.getManglingNumberContext(Tag->getParent());
3158 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3159 return;
3160 }
3161
3162 // If this tag isn't a direct child of a class, number it if it is local.
3163 Decl *ManglingContextDecl;
3164 if (MangleNumberingContext *MCtx =
3165 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3166 ManglingContextDecl)) {
3167 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3168 }
3169}
3170
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003171/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003172/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003173/// parameters to cope with template friend declarations.
3174Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3175 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003176 MultiTemplateParamsArg TemplateParams,
3177 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003178 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003179 TagDecl *Tag = 0;
3180 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3181 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003182 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003183 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003184 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003185 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003186
3187 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003188 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003189
John McCall07e91c02009-08-06 02:15:43 +00003190 // Note that the above type specs guarantee that the
3191 // type rep is a Decl, whereas in many of the others
3192 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003193 if (isa<TagDecl>(TagD))
3194 Tag = cast<TagDecl>(TagD);
3195 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3196 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003197 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003198
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003199 if (Tag) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003200 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003201 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003202 if (Tag->isInvalidDecl())
3203 return Tag;
3204 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003205
Nuno Lopese9823fa2009-12-17 11:35:26 +00003206 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3207 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3208 // or incomplete types shall not be restrict-qualified."
3209 if (TypeQuals & DeclSpec::TQ_restrict)
3210 Diag(DS.getRestrictSpecLoc(),
3211 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3212 << DS.getSourceRange();
3213 }
3214
Richard Smitha77a0a62011-08-15 21:04:07 +00003215 if (DS.isConstexprSpecified()) {
3216 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3217 // and definitions of functions and variables.
3218 if (Tag)
3219 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3220 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3221 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003222 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3223 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003224 else
3225 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3226 // Don't emit warnings after this error.
3227 return TagD;
3228 }
3229
Richard Smithb1402ae2013-03-18 22:52:47 +00003230 DiagnoseFunctionSpecifiers(DS);
3231
Douglas Gregor3dad8422009-09-26 06:47:28 +00003232 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003233 // If we're dealing with a decl but not a TagDecl, assume that
3234 // whatever routines created it handled the friendship aspect.
3235 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003236 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003237 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003238 }
John McCallaa017372011-03-22 23:00:04 +00003239
Richard Smithb1402ae2013-03-18 22:52:47 +00003240 CXXScopeSpec &SS = DS.getTypeSpecScope();
3241 bool IsExplicitSpecialization =
3242 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3243 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3244 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3245 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3246 // nested-name-specifier unless it is an explicit instantiation
3247 // or an explicit specialization.
3248 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3249 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3250 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3251 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3252 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3253 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3254 << SS.getRange();
3255 return 0;
3256 }
3257
3258 // Track whether this decl-specifier declares anything.
3259 bool DeclaresAnything = true;
3260
3261 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003262 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003263 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003264 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003265 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003266 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003267 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003268
Richard Smithb1402ae2013-03-18 22:52:47 +00003269 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003270 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003271 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003272
Richard Smithb1402ae2013-03-18 22:52:47 +00003273 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003274 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003275 CurContext->isRecord() &&
3276 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3277 // Handle 2 kinds of anonymous struct:
3278 // struct STRUCT;
3279 // and
3280 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3281 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003282 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003283 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3284 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003285 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003286 << DS.getSourceRange();
3287 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3288 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003289 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003290
3291 // Skip all the checks below if we have a type error.
3292 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3293 (TagD && TagD->isInvalidDecl()))
3294 return TagD;
3295
3296 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003297 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3298 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3299 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003300 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3301 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003302
John McCallaa017372011-03-22 23:00:04 +00003303 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003304 // Customize diagnostic for a typedef missing a name.
3305 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003306 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003307 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003308 else
3309 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003310 }
Mike Stump11289f42009-09-09 15:08:12 +00003311
Richard Smithb1402ae2013-03-18 22:52:47 +00003312 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003313 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3314 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3315 << Tag->getTagKind()
3316 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3317
Richard Smithb1402ae2013-03-18 22:52:47 +00003318 ActOnDocumentableDecl(TagD);
3319
3320 // C 6.7/2:
3321 // A declaration [...] shall declare at least a declarator [...], a tag,
3322 // or the members of an enumeration.
3323 // C++ [dcl.dcl]p3:
3324 // [If there are no declarators], and except for the declaration of an
3325 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3326 // names into the program, or shall redeclare a name introduced by a
3327 // previous declaration.
3328 if (!DeclaresAnything) {
3329 // In C, we allow this as a (popular) extension / bug. Don't bother
3330 // producing further diagnostics for redundant qualifiers after this.
3331 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3332 return TagD;
3333 }
3334
3335 // C++ [dcl.stc]p1:
3336 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3337 // init-declarator-list of the declaration shall not be empty.
3338 // C++ [dcl.fct.spec]p1:
3339 // If a cv-qualifier appears in a decl-specifier-seq, the
3340 // init-declarator-list of the declaration shall not be empty.
3341 //
3342 // Spurious qualifiers here appear to be valid in C.
3343 unsigned DiagID = diag::warn_standalone_specifier;
3344 if (getLangOpts().CPlusPlus)
3345 DiagID = diag::ext_standalone_specifier;
3346
3347 // Note that a linkage-specification sets a storage class, but
3348 // 'extern "C" struct foo;' is actually valid and not theoretically
3349 // useless.
3350 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3351 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3352 Diag(DS.getStorageClassSpecLoc(), DiagID)
3353 << DeclSpec::getSpecifierName(SCS);
3354
Richard Smithb4a9e862013-04-12 22:46:28 +00003355 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3356 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3357 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003358 if (DS.getTypeQualifiers()) {
3359 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3360 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3361 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3362 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3363 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003364 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3365 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003366 }
3367
Eli Friedmane3217952011-12-17 00:36:09 +00003368 // Warn about ignored type attributes, for example:
3369 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003370 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003371 if (!DS.getAttributes().empty()) {
3372 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3373 if (TypeSpecType == DeclSpec::TST_class ||
3374 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003375 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003376 TypeSpecType == DeclSpec::TST_union ||
3377 TypeSpecType == DeclSpec::TST_enum) {
3378 AttributeList* attrs = DS.getAttributes().getList();
3379 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003380 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003381 << attrs->getName()
3382 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3383 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003384 TypeSpecType == DeclSpec::TST_union ? 2 :
3385 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003386 attrs = attrs->getNext();
3387 }
3388 }
3389 }
John McCallaa017372011-03-22 23:00:04 +00003390
John McCall48871652010-08-21 09:40:31 +00003391 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003392}
3393
John McCallea305ed2009-12-18 10:40:03 +00003394/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003395/// check if there's an existing declaration that can't be overloaded.
3396///
3397/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003398static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3399 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003400 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003401 DeclarationName Name,
3402 SourceLocation NameLoc,
3403 unsigned diagnostic) {
3404 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3405 Sema::ForRedeclaration);
3406 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003407
John McCallea305ed2009-12-18 10:40:03 +00003408 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003409 return false;
3410
3411 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003412 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003413 assert(PrevDecl && "Expected a non-null Decl");
3414
3415 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3416 return false;
John McCall1f82f242009-11-18 22:49:29 +00003417
John McCallea305ed2009-12-18 10:40:03 +00003418 SemaRef.Diag(NameLoc, diagnostic) << Name;
3419 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003420
3421 return true;
3422}
3423
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003424/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3425/// anonymous struct or union AnonRecord into the owning context Owner
3426/// and scope S. This routine will be invoked just after we realize
3427/// that an unnamed union or struct is actually an anonymous union or
3428/// struct, e.g.,
3429///
3430/// @code
3431/// union {
3432/// int i;
3433/// float f;
3434/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3435/// // f into the surrounding scope.x
3436/// @endcode
3437///
3438/// This routine is recursive, injecting the names of nested anonymous
3439/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003440static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003441 DeclContext *Owner,
3442 RecordDecl *AnonRecord,
3443 AccessSpecifier AS,
3444 SmallVectorImpl<NamedDecl *> &Chaining,
3445 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003446 unsigned diagKind
3447 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3448 : diag::err_anonymous_struct_member_redecl;
3449
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003450 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003451
3452 // Look every FieldDecl and IndirectFieldDecl with a name.
3453 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3454 DEnd = AnonRecord->decls_end();
3455 D != DEnd; ++D) {
3456 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3457 cast<NamedDecl>(*D)->getDeclName()) {
3458 ValueDecl *VD = cast<ValueDecl>(*D);
3459 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3460 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003461 // C++ [class.union]p2:
3462 // The names of the members of an anonymous union shall be
3463 // distinct from the names of any other entity in the
3464 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003465 Invalid = true;
3466 } else {
3467 // C++ [class.union]p2:
3468 // For the purpose of name lookup, after the anonymous union
3469 // definition, the members of the anonymous union are
3470 // considered to have been defined in the scope in which the
3471 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003472 unsigned OldChainingSize = Chaining.size();
3473 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3474 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3475 PE = IF->chain_end(); PI != PE; ++PI)
3476 Chaining.push_back(*PI);
3477 else
3478 Chaining.push_back(VD);
3479
Francois Pichet783dd6e2010-11-21 06:08:52 +00003480 assert(Chaining.size() >= 2);
3481 NamedDecl **NamedChain =
3482 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3483 for (unsigned i = 0; i < Chaining.size(); i++)
3484 NamedChain[i] = Chaining[i];
3485
3486 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003487 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3488 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003489 NamedChain, Chaining.size());
3490
3491 IndirectField->setAccess(AS);
3492 IndirectField->setImplicit();
3493 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003494
3495 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003496 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003497
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003498 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003499 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003500 }
3501 }
3502
3503 return Invalid;
3504}
3505
Douglas Gregorc4df4072010-04-19 22:54:31 +00003506/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3507/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003508/// illegal input values are mapped to SC_None.
3509static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003510StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3511 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3512 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3513 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003514 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003515 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003516 case DeclSpec::SCS_extern:
3517 if (DS.isExternInLinkageSpec())
3518 return SC_None;
3519 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003520 case DeclSpec::SCS_static: return SC_Static;
3521 case DeclSpec::SCS_auto: return SC_Auto;
3522 case DeclSpec::SCS_register: return SC_Register;
3523 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003524 // Illegal SCSs map to None: error reporting is up to the caller.
3525 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003526 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003527 }
3528 llvm_unreachable("unknown storage class specifier");
3529}
3530
Richard Smithab44d5b2013-12-10 08:25:00 +00003531static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3532 assert(Record->hasInClassInitializer());
3533
3534 for (DeclContext::decl_iterator I = Record->decls_begin(),
3535 E = Record->decls_end();
3536 I != E; ++I) {
3537 FieldDecl *FD = dyn_cast<FieldDecl>(*I);
3538 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
3539 FD = IFD->getAnonField();
3540 if (FD && FD->hasInClassInitializer())
3541 return FD->getLocation();
3542 }
3543
3544 llvm_unreachable("couldn't find in-class initializer");
3545}
3546
3547static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3548 SourceLocation DefaultInitLoc) {
3549 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3550 return;
3551
3552 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3553 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3554}
3555
3556static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3557 CXXRecordDecl *AnonUnion) {
3558 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3559 return;
3560
3561 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3562}
3563
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003564/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003565/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003566/// (C++ [class.union]) and a C11 feature; anonymous structures
3567/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003568Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003569 AccessSpecifier AS,
3570 RecordDecl *Record,
3571 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003572 DeclContext *Owner = Record->getDeclContext();
3573
3574 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003575 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003576 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003577 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003578 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003579 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003580 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003581
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003582 // C and C++ require different kinds of checks for anonymous
3583 // structs/unions.
3584 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003585 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003586 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003587 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003588 if (Record->isUnion()) {
3589 // C++ [class.union]p6:
3590 // Anonymous unions declared in a named namespace or in the
3591 // global namespace shall be declared static.
3592 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3593 (isa<TranslationUnitDecl>(Owner) ||
3594 (isa<NamespaceDecl>(Owner) &&
3595 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003596 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3597 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003598
3599 // Recover by adding 'static'.
3600 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003601 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003602 }
3603 // C++ [class.union]p6:
3604 // A storage class is not allowed in a declaration of an
3605 // anonymous union in a class scope.
3606 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3607 isa<RecordDecl>(Owner)) {
3608 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003609 diag::err_anonymous_union_with_storage_spec)
3610 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003611
3612 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003613 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3614 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003615 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003616 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003617 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003618
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003619 // Ignore const/volatile/restrict qualifiers.
3620 if (DS.getTypeQualifiers()) {
3621 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3622 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003623 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003624 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3625 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003626 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003627 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003628 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003629 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3630 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003631 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003632 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003633 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003634 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003635 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3636 Diag(DS.getAtomicSpecLoc(),
3637 diag::ext_anonymous_struct_union_qualified)
3638 << Record->isUnion() << "_Atomic"
3639 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003640
3641 DS.ClearTypeQualifiers();
3642 }
3643
Mike Stump11289f42009-09-09 15:08:12 +00003644 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003645 // The member-specification of an anonymous union shall only
3646 // define non-static data members. [Note: nested types and
3647 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003648 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3649 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003650 Mem != MemEnd; ++Mem) {
3651 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3652 // C++ [class.union]p3:
3653 // An anonymous union shall not have private or protected
3654 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003655 assert(FD->getAccess() != AS_none);
3656 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003657 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3658 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3659 Invalid = true;
3660 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003661
Alexis Hunt97ab5542011-05-16 22:41:40 +00003662 // C++ [class.union]p1
3663 // An object of a class with a non-trivial constructor, a non-trivial
3664 // copy constructor, a non-trivial destructor, or a non-trivial copy
3665 // assignment operator cannot be a member of a union, nor can an
3666 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003667 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003668 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00003669 } else if ((*Mem)->isImplicit()) {
3670 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00003671 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3672 // This is a type that showed up in an
3673 // elaborated-type-specifier inside the anonymous struct or
3674 // union, but which actually declares a type outside of the
3675 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003676 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3677 if (!MemRecord->isAnonymousStructOrUnion() &&
3678 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003679 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003680 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003681 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3682 << (int)Record->isUnion();
3683 else {
3684 // This is a nested type declaration.
3685 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3686 << (int)Record->isUnion();
3687 Invalid = true;
3688 }
Richard Smith254d2662013-01-28 00:54:05 +00003689 } else {
3690 // This is an anonymous type definition within another anonymous type.
3691 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3692 // not part of standard C++.
3693 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003694 diag::ext_anonymous_record_with_anonymous_type)
3695 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003696 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00003697 } else if (isa<AccessSpecDecl>(*Mem)) {
3698 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003699 } else {
3700 // We have something that isn't a non-static data
3701 // member. Complain about it.
3702 unsigned DK = diag::err_anonymous_record_bad_member;
3703 if (isa<TypeDecl>(*Mem))
3704 DK = diag::err_anonymous_record_with_type;
3705 else if (isa<FunctionDecl>(*Mem))
3706 DK = diag::err_anonymous_record_with_function;
3707 else if (isa<VarDecl>(*Mem))
3708 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003709
3710 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003711 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003712 DK == diag::err_anonymous_record_with_type)
3713 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003714 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003715 else {
3716 Diag((*Mem)->getLocation(), DK)
3717 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003718 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003719 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003720 }
3721 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003722
3723 // C++11 [class.union]p8 (DR1460):
3724 // At most one variant member of a union may have a
3725 // brace-or-equal-initializer.
3726 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3727 Owner->isRecord())
3728 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3729 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003730 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003731
3732 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003733 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003734 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003735 Invalid = true;
3736 }
3737
John McCallfa2d6922009-10-22 23:31:08 +00003738 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003739 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003740 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003741 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003742
Mike Stump11289f42009-09-09 15:08:12 +00003743 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003744 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003745 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003746 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003747 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003748 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003749 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003750 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003751 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003752 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003753 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003754 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003755 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003756 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003757 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003758 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003759 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003760 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003761 // mutable can only appear on non-static class members, so it's always
3762 // an error here
3763 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3764 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003765 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003766 }
3767
Abramo Bagnaradff19302011-03-08 08:55:46 +00003768 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003769 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003770 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003771 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003772 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003773
3774 // Default-initialize the implicit variable. This initialization will be
3775 // trivial in almost all cases, except if a union member has an in-class
3776 // initializer:
3777 // union { int n = 0; };
3778 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003779 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003780 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003781
Richard Smithab44d5b2013-12-10 08:25:00 +00003782 // Mark this as an anonymous struct/union type.
3783 Record->setAnonymousStructOrUnion(true);
3784
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003785 // Add the anonymous struct/union object to the current
3786 // context. We'll be referencing this object when we refer to one of
3787 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003788 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003789
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003790 // Inject the members of the anonymous struct/union into the owning
3791 // context and into the identifier resolver chain for name lookup
3792 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003793 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003794 Chain.push_back(Anon);
3795
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003796 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3797 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003798 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003799
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003800 if (Invalid)
3801 Anon->setInvalidDecl();
3802
John McCall48871652010-08-21 09:40:31 +00003803 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003804}
3805
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003806/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3807/// Microsoft C anonymous structure.
3808/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3809/// Example:
3810///
3811/// struct A { int a; };
3812/// struct B { struct A; int b; };
3813///
3814/// void foo() {
3815/// B var;
3816/// var.a = 3;
3817/// }
3818///
3819Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3820 RecordDecl *Record) {
3821
3822 // If there is no Record, get the record via the typedef.
3823 if (!Record)
3824 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3825
3826 // Mock up a declarator.
3827 Declarator Dc(DS, Declarator::TypeNameContext);
3828 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3829 assert(TInfo && "couldn't build declarator info for anonymous struct");
3830
3831 // Create a declaration for this anonymous struct.
3832 NamedDecl* Anon = FieldDecl::Create(Context,
3833 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003834 DS.getLocStart(),
3835 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003836 /*IdentifierInfo=*/0,
3837 Context.getTypeDeclType(Record),
3838 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003839 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003840 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003841 Anon->setImplicit();
3842
3843 // Add the anonymous struct object to the current context.
3844 CurContext->addDecl(Anon);
3845
3846 // Inject the members of the anonymous struct into the current
3847 // context and into the identifier resolver chain for name lookup
3848 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003849 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003850 Chain.push_back(Anon);
3851
Nico Weberf8bb3de2012-02-01 00:41:00 +00003852 RecordDecl *RecordDef = Record->getDefinition();
3853 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3854 RecordDef, AS_none,
3855 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003856 Anon->setInvalidDecl();
3857
3858 return Anon;
3859}
Steve Naroff2fea1392007-09-02 02:04:30 +00003860
Douglas Gregor92751d42008-11-17 22:58:34 +00003861/// GetNameForDeclarator - Determine the full declaration name for the
3862/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003863DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003864 return GetNameFromUnqualifiedId(D.getName());
3865}
3866
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003867/// \brief Retrieves the declaration name from a parsed unqualified-id.
3868DeclarationNameInfo
3869Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3870 DeclarationNameInfo NameInfo;
3871 NameInfo.setLoc(Name.StartLocation);
3872
Douglas Gregor7861a802009-11-03 01:35:08 +00003873 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003874
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003875 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003876 case UnqualifiedId::IK_Identifier:
3877 NameInfo.setName(Name.Identifier);
3878 NameInfo.setLoc(Name.StartLocation);
3879 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003880
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003881 case UnqualifiedId::IK_OperatorFunctionId:
3882 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3883 Name.OperatorFunctionId.Operator));
3884 NameInfo.setLoc(Name.StartLocation);
3885 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3886 = Name.OperatorFunctionId.SymbolLocations[0];
3887 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3888 = Name.EndLocation.getRawEncoding();
3889 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003890
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003891 case UnqualifiedId::IK_LiteralOperatorId:
3892 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3893 Name.Identifier));
3894 NameInfo.setLoc(Name.StartLocation);
3895 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3896 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003897
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003898 case UnqualifiedId::IK_ConversionFunctionId: {
3899 TypeSourceInfo *TInfo;
3900 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3901 if (Ty.isNull())
3902 return DeclarationNameInfo();
3903 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3904 Context.getCanonicalType(Ty)));
3905 NameInfo.setLoc(Name.StartLocation);
3906 NameInfo.setNamedTypeInfo(TInfo);
3907 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003908 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003909
3910 case UnqualifiedId::IK_ConstructorName: {
3911 TypeSourceInfo *TInfo;
3912 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3913 if (Ty.isNull())
3914 return DeclarationNameInfo();
3915 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3916 Context.getCanonicalType(Ty)));
3917 NameInfo.setLoc(Name.StartLocation);
3918 NameInfo.setNamedTypeInfo(TInfo);
3919 return NameInfo;
3920 }
3921
3922 case UnqualifiedId::IK_ConstructorTemplateId: {
3923 // In well-formed code, we can only have a constructor
3924 // template-id that refers to the current context, so go there
3925 // to find the actual type being constructed.
3926 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3927 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3928 return DeclarationNameInfo();
3929
3930 // Determine the type of the class being constructed.
3931 QualType CurClassType = Context.getTypeDeclType(CurClass);
3932
3933 // FIXME: Check two things: that the template-id names the same type as
3934 // CurClassType, and that the template-id does not occur when the name
3935 // was qualified.
3936
3937 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3938 Context.getCanonicalType(CurClassType)));
3939 NameInfo.setLoc(Name.StartLocation);
3940 // FIXME: should we retrieve TypeSourceInfo?
3941 NameInfo.setNamedTypeInfo(0);
3942 return NameInfo;
3943 }
3944
3945 case UnqualifiedId::IK_DestructorName: {
3946 TypeSourceInfo *TInfo;
3947 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3948 if (Ty.isNull())
3949 return DeclarationNameInfo();
3950 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3951 Context.getCanonicalType(Ty)));
3952 NameInfo.setLoc(Name.StartLocation);
3953 NameInfo.setNamedTypeInfo(TInfo);
3954 return NameInfo;
3955 }
3956
3957 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003958 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003959 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3960 return Context.getNameForTemplate(TName, TNameLoc);
3961 }
3962
3963 } // switch (Name.getKind())
3964
David Blaikie83d382b2011-09-23 05:06:16 +00003965 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003966}
3967
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003968static QualType getCoreType(QualType Ty) {
3969 do {
3970 if (Ty->isPointerType() || Ty->isReferenceType())
3971 Ty = Ty->getPointeeType();
3972 else if (Ty->isArrayType())
3973 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3974 else
3975 return Ty.withoutLocalFastQualifiers();
3976 } while (true);
3977}
3978
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003979/// hasSimilarParameters - Determine whether the C++ functions Declaration
3980/// and Definition have "nearly" matching parameters. This heuristic is
3981/// used to improve diagnostics in the case where an out-of-line function
3982/// definition doesn't match any declaration within the class or namespace.
3983/// Also sets Params to the list of indices to the parameters that differ
3984/// between the declaration and the definition. If hasSimilarParameters
3985/// returns true and Params is empty, then all of the parameters match.
3986static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003987 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003988 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003989 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003990 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003991 if (Declaration->param_size() != Definition->param_size())
3992 return false;
3993 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3994 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3995 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3996
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003997 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00003998 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003999 continue;
4000
4001 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4002 QualType DefParamBaseTy = getCoreType(DefParamTy);
4003 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4004 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4005
4006 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4007 (DeclTyName && DeclTyName == DefTyName))
4008 Params.push_back(Idx);
4009 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004010 return false;
4011 }
4012
4013 return true;
4014}
4015
John McCall99b2fe52010-04-29 23:50:39 +00004016/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4017/// declarator needs to be rebuilt in the current instantiation.
4018/// Any bits of declarator which appear before the name are valid for
4019/// consideration here. That's specifically the type in the decl spec
4020/// and the base type in any member-pointer chunks.
4021static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4022 DeclarationName Name) {
4023 // The types we specifically need to rebuild are:
4024 // - typenames, typeofs, and decltypes
4025 // - types which will become injected class names
4026 // Of course, we also need to rebuild any type referencing such a
4027 // type. It's safest to just say "dependent", but we call out a
4028 // few cases here.
4029
4030 DeclSpec &DS = D.getMutableDeclSpec();
4031 switch (DS.getTypeSpecType()) {
4032 case DeclSpec::TST_typename:
4033 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004034 case DeclSpec::TST_underlyingType:
4035 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004036 // Grab the type from the parser.
4037 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004038 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004039 if (T.isNull() || !T->isDependentType()) break;
4040
4041 // Make sure there's a type source info. This isn't really much
4042 // of a waste; most dependent types should have type source info
4043 // attached already.
4044 if (!TSI)
4045 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4046
4047 // Rebuild the type in the current instantiation.
4048 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4049 if (!TSI) return true;
4050
4051 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004052 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4053 DS.UpdateTypeRep(LocType);
4054 break;
4055 }
4056
Richard Smith1620ebd2012-10-01 20:35:07 +00004057 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004058 case DeclSpec::TST_typeofExpr: {
4059 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004060 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004061 if (Result.isInvalid()) return true;
4062 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004063 break;
4064 }
4065
4066 default:
4067 // Nothing to do for these decl specs.
4068 break;
4069 }
4070
4071 // It doesn't matter what order we do this in.
4072 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4073 DeclaratorChunk &Chunk = D.getTypeObject(I);
4074
4075 // The only type information in the declarator which can come
4076 // before the declaration name is the base type of a member
4077 // pointer.
4078 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4079 continue;
4080
4081 // Rebuild the scope specifier in-place.
4082 CXXScopeSpec &SS = Chunk.Mem.Scope();
4083 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4084 return true;
4085 }
4086
4087 return false;
4088}
4089
Anders Carlsson1052fd72011-07-04 16:28:17 +00004090Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004091 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004092 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004093
4094 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004095 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004096 Dcl->setTopLevelDeclInObjCContainer();
4097
4098 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004099}
4100
Richard Smithdda56e42011-04-15 14:24:37 +00004101/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4102/// If T is the name of a class, then each of the following shall have a
4103/// name different from T:
4104/// - every static data member of class T;
4105/// - every member function of class T
4106/// - every member of class T that is itself a type;
4107/// \returns true if the declaration name violates these rules.
4108bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4109 DeclarationNameInfo NameInfo) {
4110 DeclarationName Name = NameInfo.getName();
4111
4112 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4113 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4114 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4115 return true;
4116 }
4117
4118 return false;
4119}
Douglas Gregor31feb332012-03-17 23:06:31 +00004120
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004121/// \brief Diagnose a declaration whose declarator-id has the given
4122/// nested-name-specifier.
4123///
4124/// \param SS The nested-name-specifier of the declarator-id.
4125///
4126/// \param DC The declaration context to which the nested-name-specifier
4127/// resolves.
4128///
4129/// \param Name The name of the entity being declared.
4130///
4131/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004132///
4133/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004134bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004135 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004136 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004137 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004138 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004139 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004140
4141 // If the user provided a superfluous scope specifier that refers back to the
4142 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004143 //
4144 // class X {
4145 // void X::f();
4146 // };
Richard Smitha2302242013-12-05 07:51:02 +00004147 //
4148 // Note, it was once ill-formed to give redundant qualification in all
4149 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004150 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004151 if (Cur->isRecord()) {
4152 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4153 : diag::err_member_extra_qualification)
4154 << Name << FixItHint::CreateRemoval(SS.getRange());
4155 SS.clear();
4156 } else {
4157 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4158 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004159 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004160 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004161
4162 // Check whether the qualifying scope encloses the scope of the original
4163 // declaration.
4164 if (!Cur->Encloses(DC)) {
4165 if (Cur->isRecord())
4166 Diag(Loc, diag::err_member_qualification)
4167 << Name << SS.getRange();
4168 else if (isa<TranslationUnitDecl>(DC))
4169 Diag(Loc, diag::err_invalid_declarator_global_scope)
4170 << Name << SS.getRange();
4171 else if (isa<FunctionDecl>(Cur))
4172 Diag(Loc, diag::err_invalid_declarator_in_function)
4173 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004174 else if (isa<BlockDecl>(Cur))
4175 Diag(Loc, diag::err_invalid_declarator_in_block)
4176 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004177 else
4178 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004179 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004180
Douglas Gregor31feb332012-03-17 23:06:31 +00004181 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004182 }
4183
4184 if (Cur->isRecord()) {
4185 // Cannot qualify members within a class.
4186 Diag(Loc, diag::err_member_qualification)
4187 << Name << SS.getRange();
4188 SS.clear();
4189
4190 // C++ constructors and destructors with incorrect scopes can break
4191 // our AST invariants by having the wrong underlying types. If
4192 // that's the case, then drop this declaration entirely.
4193 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4194 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4195 !Context.hasSameType(Name.getCXXNameType(),
4196 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4197 return true;
4198
4199 return false;
4200 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004201
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004202 // C++11 [dcl.meaning]p1:
4203 // [...] "The nested-name-specifier of the qualified declarator-id shall
4204 // not begin with a decltype-specifer"
4205 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4206 while (SpecLoc.getPrefix())
4207 SpecLoc = SpecLoc.getPrefix();
4208 if (dyn_cast_or_null<DecltypeType>(
4209 SpecLoc.getNestedNameSpecifier()->getAsType()))
4210 Diag(Loc, diag::err_decltype_in_declarator)
4211 << SpecLoc.getTypeLoc().getSourceRange();
4212
Douglas Gregor31feb332012-03-17 23:06:31 +00004213 return false;
4214}
4215
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004216NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4217 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004218 // TODO: consider using NameInfo for diagnostic.
4219 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4220 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004221
Chris Lattner02c04392007-07-25 00:24:17 +00004222 // All of these full declarators require an identifier. If it doesn't have
4223 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004224 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004225 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004226 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004227 diag::err_declarator_need_ident)
4228 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004229 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004230 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4231 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004232
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004233 // The scope passed in may not be a decl scope. Zip up the scope tree until
4234 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004235 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004236 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004237 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004238
John McCall99b2fe52010-04-29 23:50:39 +00004239 DeclContext *DC = CurContext;
4240 if (D.getCXXScopeSpec().isInvalid())
4241 D.setInvalidType();
4242 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004243 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4244 UPPC_DeclarationQualifier))
4245 return 0;
4246
John McCall99b2fe52010-04-29 23:50:39 +00004247 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4248 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004249 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004250 // If we could not compute the declaration context, it's because the
4251 // declaration context is dependent but does not refer to a class,
4252 // class template, or class template partial specialization. Complain
4253 // and return early, to avoid the coming semantic disaster.
4254 Diag(D.getIdentifierLoc(),
4255 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004256 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004257 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004258 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004259 }
John McCall99b2fe52010-04-29 23:50:39 +00004260 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004261
John McCall99b2fe52010-04-29 23:50:39 +00004262 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004263 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004264 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004265
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004266 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4267 Diag(D.getIdentifierLoc(),
4268 diag::err_member_def_undefined_record)
4269 << Name << DC << D.getCXXScopeSpec().getRange();
4270 D.setInvalidType();
4271 } else if (!D.getDeclSpec().isFriendSpecified()) {
4272 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4273 Name, D.getIdentifierLoc())) {
4274 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004275 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004276
4277 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004278 }
John McCall99b2fe52010-04-29 23:50:39 +00004279 }
4280
4281 // Check whether we need to rebuild the type of the given
4282 // declaration in the current instantiation.
4283 if (EnteringContext && IsDependentContext &&
4284 TemplateParamLists.size() != 0) {
4285 ContextRAII SavedContext(*this, DC);
4286 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4287 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004288 }
4289 }
Richard Smithdda56e42011-04-15 14:24:37 +00004290
4291 if (DiagnoseClassNameShadow(DC, NameInfo))
4292 // If this is a typedef, we'll end up spewing multiple diagnostics.
4293 // Just return early; it's safer.
4294 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4295 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004296
John McCall8cb7bdf2010-06-04 23:28:52 +00004297 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4298 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004299
Douglas Gregor506bd562010-12-13 22:49:22 +00004300 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4301 UPPC_DeclarationType))
4302 D.setInvalidType();
4303
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004304 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004305 ForRedeclaration);
4306
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004307 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004308 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004309 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004310 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004311
4312 // If the declaration we're planning to build will be a function
4313 // or object with linkage, then look for another declaration with
4314 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004315 //
4316 // If the declaration we're planning to build will be declared with
4317 // external linkage in the translation unit, create any builtin with
4318 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004319 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4320 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004321 else if (CurContext->isFunctionOrMethod() &&
4322 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4323 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004324 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004325 CreateBuiltins =
4326 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4327 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4328 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4329 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004330
4331 if (IsLinkageLookup)
4332 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004333
Richard Smith1c34fb72013-08-13 18:18:50 +00004334 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004335 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004336 LookupQualifiedName(Previous, DC);
4337
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004338 // C++ [dcl.meaning]p1:
4339 // When the declarator-id is qualified, the declaration shall refer to a
4340 // previously declared member of the class or namespace to which the
4341 // qualifier refers (or, in the case of a namespace, of an element of the
4342 // inline namespace set of that namespace (7.3.1)) or to a specialization
4343 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004344 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004345 // Note that we already checked the context above, and that we do not have
4346 // enough information to make sure that Previous contains the declaration
4347 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004348 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004349 // class X {
4350 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004351 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004352 // };
4353 //
Douglas Gregorad590502008-12-15 23:53:10 +00004354 // void X::f(int) { } // ill-formed
4355 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004356 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004357 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004358 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004359
4360 // C++ [dcl.meaning]p1:
4361 // [...] the member shall not merely have been introduced by a
4362 // using-declaration in the scope of the class or namespace nominated by
4363 // the nested-name-specifier of the declarator-id.
4364 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004365 }
4366
John McCall1f82f242009-11-18 22:49:29 +00004367 if (Previous.isSingleResult() &&
4368 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004369 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004370 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004371 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4372 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004373
Douglas Gregor5101c242008-12-05 18:15:24 +00004374 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004375 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004376 }
4377
Douglas Gregor83a586e2008-04-13 21:07:44 +00004378 // In C++, the previous declaration we find might be a tag type
4379 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004380 // tag type. Note that this does does not apply if we're declaring a
4381 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004382 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004383 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004384 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004385
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004386 // Check that there are no default arguments other than in the parameters
4387 // of a function declaration (C++ only).
4388 if (getLangOpts().CPlusPlus)
4389 CheckExtraCXXDefaultArguments(D);
4390
Nico Webercb4c7f42012-12-23 00:40:46 +00004391 NamedDecl *New;
4392
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004393 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004394 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004395 if (TemplateParamLists.size()) {
4396 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004397 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004398 }
Mike Stump11289f42009-09-09 15:08:12 +00004399
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004400 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004401 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004402 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004403 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004404 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004405 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004406 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4407 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004408 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004409
4410 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004411 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004412
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004413 // If this has an identifier and is not an invalid redeclaration or
4414 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004415 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004416 !(D.isRedeclaration() && New->isInvalidDecl())) {
4417 // Only make a locally-scoped extern declaration visible if it is the first
4418 // declaration of this entity. Qualified lookup for such an entity should
4419 // only find this declaration if there is no visible declaration of it.
4420 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4421 PushOnScopeChains(New, S, AddToContext);
4422 if (!AddToContext)
4423 CurContext->addHiddenDecl(New);
4424 }
Mike Stump11289f42009-09-09 15:08:12 +00004425
John McCall48871652010-08-21 09:40:31 +00004426 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004427}
4428
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004429/// Helper method to turn variable array types into constant array
4430/// types in certain situations which would otherwise be errors (for
4431/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004432static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4433 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004434 bool &SizeIsNegative,
4435 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004436 // This method tries to turn a variable array into a constant
4437 // array even when the size isn't an ICE. This is necessary
4438 // for compatibility with code that depends on gcc's buggy
4439 // constant expression folding, like struct {char x[(int)(char*)2];}
4440 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004441 Oversized = 0;
4442
4443 if (T->isDependentType())
4444 return QualType();
4445
John McCall8ccfcb52009-09-24 19:53:00 +00004446 QualifierCollector Qs;
4447 const Type *Ty = Qs.strip(T);
4448
4449 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004450 QualType Pointee = PTy->getPointeeType();
4451 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004452 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4453 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004454 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004455 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004456 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004457 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004458 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4459 QualType Inner = PTy->getInnerType();
4460 QualType FixedType =
4461 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4462 Oversized);
4463 if (FixedType.isNull()) return FixedType;
4464 FixedType = Context.getParenType(FixedType);
4465 return Qs.apply(Context, FixedType);
4466 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004467
4468 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004469 if (!VLATy)
4470 return QualType();
4471 // FIXME: We should probably handle this case
4472 if (VLATy->getElementType()->isVariablyModifiedType())
4473 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004474
Richard Smith42d3af92011-12-07 00:43:50 +00004475 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004476 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004477 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004478 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004479
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004480 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004481 if (Res.isSigned() && Res.isNegative()) {
4482 SizeIsNegative = true;
4483 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004484 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004485
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004486 // Check whether the array is too large to be addressed.
4487 unsigned ActiveSizeBits
4488 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4489 Res);
4490 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4491 Oversized = Res;
4492 return QualType();
4493 }
4494
4495 return Context.getConstantArrayType(VLATy->getElementType(),
4496 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004497}
4498
Abramo Bagnara341ab732012-11-08 14:44:42 +00004499static void
4500FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004501 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4502 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4503 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4504 DstPTL.getPointeeLoc());
4505 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004506 return;
4507 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004508 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4509 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4510 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4511 DstPTL.getInnerLoc());
4512 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4513 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004514 return;
4515 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004516 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4517 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4518 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4519 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004520 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004521 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4522 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4523 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004524}
4525
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004526/// Helper method to turn variable array types into constant array
4527/// types in certain situations which would otherwise be errors (for
4528/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004529static TypeSourceInfo*
4530TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4531 ASTContext &Context,
4532 bool &SizeIsNegative,
4533 llvm::APSInt &Oversized) {
4534 QualType FixedTy
4535 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4536 SizeIsNegative, Oversized);
4537 if (FixedTy.isNull())
4538 return 0;
4539 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4540 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4541 FixedTInfo->getTypeLoc());
4542 return FixedTInfo;
4543}
4544
Richard Smith78165b52013-01-10 23:43:47 +00004545/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004546/// that it can be found later for redeclarations. We include any extern "C"
4547/// declaration that is not visible in the translation unit here, not just
4548/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004549void
Richard Smith39b79682013-06-18 20:15:12 +00004550Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004551 if (!getLangOpts().CPlusPlus &&
4552 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4553 // Don't need to track declarations in the TU in C.
4554 return;
4555
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004556 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004557 // FIXME: There can be multiple such declarations if they are functions marked
4558 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004559 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004560}
4561
Richard Smith39b79682013-06-18 20:15:12 +00004562NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004563 if (ExternalSource) {
4564 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004565 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004566 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004567 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004568 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4569 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004570 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4571 if (Pos == LocallyScopedExternCDecls.end())
4572 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004573 }
4574 }
Richard Smith39b79682013-06-18 20:15:12 +00004575
4576 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004577 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004578}
4579
Eli Friedman574c7452009-04-07 19:37:57 +00004580/// \brief Diagnose function specifiers on a declaration of an identifier that
4581/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004582void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004583 // FIXME: We should probably indicate the identifier in question to avoid
4584 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004585 if (DS.isInlineSpecified())
4586 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004587 diag::err_inline_non_function);
4588
Richard Smithb1402ae2013-03-18 22:52:47 +00004589 if (DS.isVirtualSpecified())
4590 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004591 diag::err_virtual_non_function);
4592
Richard Smithb1402ae2013-03-18 22:52:47 +00004593 if (DS.isExplicitSpecified())
4594 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004595 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004596
Richard Smithb1402ae2013-03-18 22:52:47 +00004597 if (DS.isNoreturnSpecified())
4598 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004599 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004600}
4601
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004602NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004603Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004604 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004605 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4606 if (D.getCXXScopeSpec().isSet()) {
4607 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4608 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004609 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004610 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004611 DC = CurContext;
4612 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004613 }
4614
Richard Smithb1402ae2013-03-18 22:52:47 +00004615 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004616
Richard Smitha77a0a62011-08-15 21:04:07 +00004617 if (D.getDeclSpec().isConstexprSpecified())
4618 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4619 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004620
Douglas Gregord8f446f2010-07-13 06:37:01 +00004621 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4622 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4623 << D.getName().getSourceRange();
4624 return 0;
4625 }
4626
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004627 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004628 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004629
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004630 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004631 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004632
Richard Smith3f1b5d02011-05-05 21:57:07 +00004633 CheckTypedefForVariablyModifiedType(S, NewTD);
4634
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004635 bool Redeclaration = D.isRedeclaration();
4636 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4637 D.setRedeclaration(Redeclaration);
4638 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004639}
4640
Richard Smith3f1b5d02011-05-05 21:57:07 +00004641void
4642Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004643 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4644 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004645 // Note that variably modified types must be fixed before merging the decl so
4646 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004647 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4648 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004649 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004650 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004651
Chris Lattner9fecd742009-04-19 05:21:20 +00004652 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004653 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004654 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004655 TypeSourceInfo *FixedTInfo =
4656 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4657 SizeIsNegative,
4658 Oversized);
4659 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004660 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004661 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004662 } else {
4663 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004664 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004665 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004666 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004667 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004668 Diag(NewTD->getLocation(), diag::err_array_too_large)
4669 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004670 else
Richard Smithdda56e42011-04-15 14:24:37 +00004671 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004672 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004673 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004674 }
4675 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004676}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004677
Richard Smith3f1b5d02011-05-05 21:57:07 +00004678
4679/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4680/// declares a typedef-name, either using the 'typedef' type specifier or via
4681/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4682NamedDecl*
4683Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4684 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004685 // Merge the decl with the existing one if appropriate. If the decl is
4686 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004687 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4688 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004689 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004690 if (!Previous.empty()) {
4691 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004692 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004693 }
4694
Douglas Gregor27821ce2009-07-07 16:35:42 +00004695 // If this is the C FILE type, notify the AST context.
4696 if (IdentifierInfo *II = NewTD->getIdentifier())
4697 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004698 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004699 if (II->isStr("FILE"))
4700 Context.setFILEDecl(NewTD);
4701 else if (II->isStr("jmp_buf"))
4702 Context.setjmp_bufDecl(NewTD);
4703 else if (II->isStr("sigjmp_buf"))
4704 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004705 else if (II->isStr("ucontext_t"))
4706 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004707 }
4708
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004709 return NewTD;
4710}
4711
Douglas Gregor5d68a202009-02-24 19:23:27 +00004712/// \brief Determines whether the given declaration is an out-of-scope
4713/// previous declaration.
4714///
4715/// This routine should be invoked when name lookup has found a
4716/// previous declaration (PrevDecl) that is not in the scope where a
4717/// new declaration by the same name is being introduced. If the new
4718/// declaration occurs in a local scope, previous declarations with
4719/// linkage may still be considered previous declarations (C99
4720/// 6.2.2p4-5, C++ [basic.link]p6).
4721///
4722/// \param PrevDecl the previous declaration found by name
4723/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004724///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004725/// \param DC the context in which the new declaration is being
4726/// declared.
4727///
4728/// \returns true if PrevDecl is an out-of-scope previous declaration
4729/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004730static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004731isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4732 ASTContext &Context) {
4733 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004734 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004735
Douglas Gregoreddf4332009-02-24 20:03:32 +00004736 if (!PrevDecl->hasLinkage())
4737 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004738
David Blaikiebbafb8a2012-03-11 07:00:24 +00004739 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004740 // C++ [basic.link]p6:
4741 // If there is a visible declaration of an entity with linkage
4742 // having the same name and type, ignoring entities declared
4743 // outside the innermost enclosing namespace scope, the block
4744 // scope declaration declares that same entity and receives the
4745 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004746 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004747 if (!OuterContext->isFunctionOrMethod())
4748 // This rule only applies to block-scope declarations.
4749 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004750
4751 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4752 if (PrevOuterContext->isRecord())
4753 // We found a member function: ignore it.
4754 return false;
4755
4756 // Find the innermost enclosing namespace for the new and
4757 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004758 OuterContext = OuterContext->getEnclosingNamespaceContext();
4759 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004760
Douglas Gregorfcee9462010-08-27 22:55:10 +00004761 // The previous declaration is in a different namespace, so it
4762 // isn't the same function.
4763 if (!OuterContext->Equals(PrevOuterContext))
4764 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004765 }
4766
Douglas Gregor5d68a202009-02-24 19:23:27 +00004767 return true;
4768}
4769
John McCall3e11ebe2010-03-15 10:12:16 +00004770static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4771 CXXScopeSpec &SS = D.getCXXScopeSpec();
4772 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004773 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004774}
4775
John McCall31168b02011-06-15 23:02:42 +00004776bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4777 QualType type = decl->getType();
4778 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4779 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4780 // Various kinds of declaration aren't allowed to be __autoreleasing.
4781 unsigned kind = -1U;
4782 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4783 if (var->hasAttr<BlocksAttr>())
4784 kind = 0; // __block
4785 else if (!var->hasLocalStorage())
4786 kind = 1; // global
4787 } else if (isa<ObjCIvarDecl>(decl)) {
4788 kind = 3; // ivar
4789 } else if (isa<FieldDecl>(decl)) {
4790 kind = 2; // field
4791 }
4792
4793 if (kind != -1U) {
4794 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4795 << kind;
4796 }
4797 } else if (lifetime == Qualifiers::OCL_None) {
4798 // Try to infer lifetime.
4799 if (!type->isObjCLifetimeType())
4800 return false;
4801
4802 lifetime = type->getObjCARCImplicitLifetime();
4803 type = Context.getLifetimeQualifiedType(type, lifetime);
4804 decl->setType(type);
4805 }
4806
4807 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4808 // Thread-local variables cannot have lifetime.
4809 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004810 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004811 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004812 << var->getType();
4813 return true;
4814 }
4815 }
4816
4817 return false;
4818}
4819
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004820static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4821 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004822 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004823 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004824 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4825 ND.dropAttr<WeakAttr>();
4826 }
4827 }
4828 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004829 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004830 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4831 ND.dropAttr<WeakRefAttr>();
4832 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004833 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004834
4835 // 'selectany' only applies to externally visible varable declarations.
4836 // It does not apply to functions.
4837 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4838 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4839 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4840 ND.dropAttr<SelectAnyAttr>();
4841 }
4842 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004843}
4844
John McCallc87d9722013-04-02 02:48:58 +00004845/// Given that we are within the definition of the given function,
4846/// will that definition behave like C99's 'inline', where the
4847/// definition is discarded except for optimization purposes?
4848static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4849 // Try to avoid calling GetGVALinkageForFunction.
4850
4851 // All cases of this require the 'inline' keyword.
4852 if (!FD->isInlined()) return false;
4853
4854 // This is only possible in C++ with the gnu_inline attribute.
4855 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4856 return false;
4857
4858 // Okay, go ahead and call the relatively-more-expensive function.
4859
4860#ifndef NDEBUG
4861 // AST quite reasonably asserts that it's working on a function
4862 // definition. We don't really have a way to tell it that we're
4863 // currently defining the function, so just lie to it in +Asserts
4864 // builds. This is an awful hack.
4865 FD->setLazyBody(1);
4866#endif
4867
4868 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4869
4870#ifndef NDEBUG
4871 FD->setLazyBody(0);
4872#endif
4873
4874 return isC99Inline;
4875}
4876
Richard Smithac974a32013-06-30 09:48:50 +00004877/// Determine whether a variable is extern "C" prior to attaching
4878/// an initializer. We can't just call isExternC() here, because that
4879/// will also compute and cache whether the declaration is externally
4880/// visible, which might change when we attach the initializer.
4881///
4882/// This can only be used if the declaration is known to not be a
4883/// redeclaration of an internal linkage declaration.
4884///
4885/// For instance:
4886///
4887/// auto x = []{};
4888///
4889/// Attaching the initializer here makes this declaration not externally
4890/// visible, because its type has internal linkage.
4891///
4892/// FIXME: This is a hack.
4893template<typename T>
4894static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4895 if (S.getLangOpts().CPlusPlus) {
4896 // In C++, the overloadable attribute negates the effects of extern "C".
4897 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4898 return false;
4899 }
4900 return D->isExternC();
4901}
4902
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004903static bool shouldConsiderLinkage(const VarDecl *VD) {
4904 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4905 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004906 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004907 if (DC->isFileContext())
4908 return true;
4909 if (DC->isRecord())
4910 return false;
4911 llvm_unreachable("Unexpected context");
4912}
4913
4914static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4915 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4916 if (DC->isFileContext() || DC->isFunctionOrMethod())
4917 return true;
4918 if (DC->isRecord())
4919 return false;
4920 llvm_unreachable("Unexpected context");
4921}
4922
Richard Smith541b38b2013-09-20 01:15:31 +00004923/// Adjust the \c DeclContext for a function or variable that might be a
4924/// function-local external declaration.
4925bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4926 if (!DC->isFunctionOrMethod())
4927 return false;
4928
4929 // If this is a local extern function or variable declared within a function
4930 // template, don't add it into the enclosing namespace scope until it is
4931 // instantiated; it might have a dependent type right now.
4932 if (DC->isDependentContext())
4933 return true;
4934
4935 // C++11 [basic.link]p7:
4936 // When a block scope declaration of an entity with linkage is not found to
4937 // refer to some other declaration, then that entity is a member of the
4938 // innermost enclosing namespace.
4939 //
4940 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4941 // semantically-enclosing namespace, not a lexically-enclosing one.
4942 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4943 DC = DC->getParent();
4944 return true;
4945}
4946
Larisse Voufo39a1e502013-08-06 01:03:05 +00004947NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00004948Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004949 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004950 MultiTemplateParamsArg TemplateParamLists,
4951 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004952 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004953 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004954
Douglas Gregorc4df4072010-04-19 22:54:31 +00004955 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00004956 VarDecl::StorageClass SC =
4957 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00004958
Richard Smith541b38b2013-09-20 01:15:31 +00004959 DeclContext *OriginalDC = DC;
4960 bool IsLocalExternDecl = SC == SC_Extern &&
4961 adjustContextForLocalExternDecl(DC);
4962
Richard Smith5990db62013-04-15 08:33:22 +00004963 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004964 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4965 // half array type (unless the cl_khr_fp16 extension is enabled).
4966 if (Context.getBaseElementType(R)->isHalfType()) {
4967 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4968 D.setInvalidType();
4969 }
4970 }
4971
Douglas Gregorc4df4072010-04-19 22:54:31 +00004972 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004973 // mutable can only appear on non-static class members, so it's always
4974 // an error here
4975 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004976 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004977 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004978 }
John McCallc87d9722013-04-02 02:48:58 +00004979
Richard Smithf2c9afc2013-06-17 01:34:01 +00004980 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4981 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4982 D.getDeclSpec().getStorageClassSpecLoc())) {
4983 // In C++11, the 'register' storage class specifier is deprecated.
4984 // Suppress the warning in system macros, it's used in macros in some
4985 // popular C system headers, such as in glibc's htonl() macro.
4986 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4987 diag::warn_deprecated_register)
4988 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4989 }
4990
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004991 IdentifierInfo *II = Name.getAsIdentifierInfo();
4992 if (!II) {
4993 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00004994 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004995 return 0;
4996 }
4997
Richard Smithb1402ae2013-03-18 22:52:47 +00004998 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00004999
Douglas Gregor212cab32009-03-11 20:22:50 +00005000 if (!DC->isRecord() && S->getFnParent() == 0) {
5001 // C99 6.9p2: The storage-class specifiers auto and register shall not
5002 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00005003 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005004 // If this is a register variable with an asm label specified, then this
5005 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00005006 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005007 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5008 else
5009 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005010 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005011 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005012 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005013
David Blaikiebbafb8a2012-03-11 07:00:24 +00005014 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005015 // Set up the special work-group-local storage class for variables in the
5016 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005017 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005018 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005019 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005020
Guy Benyei61054192013-02-07 10:55:47 +00005021 // OpenCL v1.2 s6.9.b p4:
5022 // The sampler type cannot be used with the __local and __global address
5023 // space qualifiers.
5024 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5025 R.getAddressSpace() == LangAS::opencl_global)) {
5026 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5027 }
5028
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005029 // OpenCL 1.2 spec, p6.9 r:
5030 // The event type cannot be used to declare a program scope variable.
5031 // The event type cannot be used with the __local, __constant and __global
5032 // address space qualifiers.
5033 if (R->isEventT()) {
5034 if (S->getParent() == 0) {
5035 Diag(D.getLocStart(), diag::err_event_t_global_var);
5036 D.setInvalidType();
5037 }
5038
5039 if (R.getAddressSpace()) {
5040 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5041 D.setInvalidType();
5042 }
5043 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005044 }
5045
Larisse Voufo39a1e502013-08-06 01:03:05 +00005046 bool IsExplicitSpecialization = false;
5047 bool IsVariableTemplateSpecialization = false;
5048 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005049 bool IsVariableTemplate = false;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005050 VarDecl *NewVD = 0;
5051 VarTemplateDecl *NewTemplate = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00005052 TemplateParameterList *TemplateParams = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005053 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005054 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005055 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005056 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005057
5058 if (D.isInvalidType())
5059 NewVD->setInvalidDecl();
5060 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005061 bool Invalid = false;
5062
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005063 if (DC->isRecord() && !CurContext->isRecord()) {
5064 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005065 switch (SC) {
5066 case SC_None:
5067 break;
5068 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005069 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5070 diag::err_static_out_of_line)
5071 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005072 break;
5073 case SC_Auto:
5074 case SC_Register:
5075 case SC_Extern:
5076 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5077 // to names of variables declared in a block or to function parameters.
5078 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5079 // of class members
5080
5081 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5082 diag::err_storage_class_for_static_member)
5083 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5084 break;
5085 case SC_PrivateExtern:
5086 llvm_unreachable("C storage class in c++!");
5087 case SC_OpenCLWorkGroupLocal:
5088 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005089 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005090 }
5091
Richard Smith42973752012-02-16 20:41:22 +00005092 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005093 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5094 if (RD->isLocalClass())
5095 Diag(D.getIdentifierLoc(),
5096 diag::err_static_data_member_not_allowed_in_local_class)
5097 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005098
Richard Smith42973752012-02-16 20:41:22 +00005099 // C++98 [class.union]p1: If a union contains a static data member,
5100 // the program is ill-formed. C++11 drops this restriction.
5101 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005102 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005103 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005104 ? diag::warn_cxx98_compat_static_data_member_in_union
5105 : diag::ext_static_data_member_in_union) << Name;
5106 // We conservatively disallow static data members in anonymous structs.
5107 else if (!RD->getDeclName())
5108 Diag(D.getIdentifierLoc(),
5109 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005110 << Name << RD->isUnion();
5111 }
5112 }
5113
5114 // Match up the template parameter lists with the scope specifier, then
5115 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005116 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5117 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5118 D.getCXXScopeSpec(), TemplateParamLists,
5119 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005120
Richard Smithbeef3452014-01-16 23:39:20 +00005121 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
5122 !TemplateParams) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005123 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5124
5125 // We have encountered something that the user meant to be a
5126 // specialization (because it has explicitly-specified template
5127 // arguments) but that was not introduced with a "template<>" (or had
5128 // too few of them).
5129 // FIXME: Differentiate between attempts for explicit instantiations
5130 // (starting with "template") and the rest.
5131 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5132 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5133 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5134 "template<> ");
5135 IsVariableTemplateSpecialization = true;
Richard Smithbeef3452014-01-16 23:39:20 +00005136 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(),
5137 SourceLocation(), 0, 0,
5138 SourceLocation());
5139 }
5140
5141 if (TemplateParams) {
5142 if (!TemplateParams->size() &&
5143 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5144 // There is an extraneous 'template<>' for this variable. Complain
5145 // about it, but allow the declaration of the variable.
5146 Diag(TemplateParams->getTemplateLoc(),
5147 diag::err_template_variable_noparams)
5148 << II
5149 << SourceRange(TemplateParams->getTemplateLoc(),
5150 TemplateParams->getRAngleLoc());
5151 TemplateParams = 0;
5152 } else {
5153 // Only C++1y supports variable templates (N3651).
5154 Diag(D.getIdentifierLoc(),
5155 getLangOpts().CPlusPlus1y
5156 ? diag::warn_cxx11_compat_variable_template
5157 : diag::ext_variable_template);
5158
5159 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5160 // This is an explicit specialization or a partial specialization.
5161 // FIXME: Check that we can declare a specialization here.
5162 IsVariableTemplateSpecialization = true;
5163 IsPartialSpecialization = TemplateParams->size() > 0;
5164 } else { // if (TemplateParams->size() > 0)
5165 // This is a template declaration.
5166 IsVariableTemplate = true;
5167
5168 // Check that we can declare a template here.
5169 if (CheckTemplateDeclScope(S, TemplateParams))
5170 return 0;
5171 }
5172 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005173 }
Mike Stump11289f42009-09-09 15:08:12 +00005174
Larisse Voufo39a1e502013-08-06 01:03:05 +00005175 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005176 SourceLocation TemplateKWLoc =
5177 TemplateParamLists.size() > 0
5178 ? TemplateParamLists[0]->getTemplateLoc()
5179 : SourceLocation();
5180 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005181 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005182 IsPartialSpecialization);
5183 if (Res.isInvalid())
5184 return 0;
5185 NewVD = cast<VarDecl>(Res.get());
5186 AddToScope = false;
5187 } else
5188 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5189 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005190
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005191 // If this is supposed to be a variable template, create it as such.
5192 if (IsVariableTemplate) {
5193 NewTemplate =
5194 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005195 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005196 NewVD->setDescribedVarTemplate(NewTemplate);
5197 }
5198
Richard Smithb2bc2e62011-02-21 20:05:19 +00005199 // If this decl has an auto type in need of deduction, make a note of the
5200 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005201 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005202 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005203
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005204 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005205 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005206 if (NewTemplate)
5207 NewTemplate->setInvalidDecl();
5208 }
Mike Stump11289f42009-09-09 15:08:12 +00005209
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005210 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005211
Larisse Voufo39a1e502013-08-06 01:03:05 +00005212 // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5213 if (TemplateParams && TemplateParamLists.size() > 1 &&
5214 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5215 NewVD->setTemplateParameterListsInfo(
5216 Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5217 } else if (IsVariableTemplateSpecialization ||
5218 (!TemplateParams && TemplateParamLists.size() > 0 &&
5219 (D.getCXXScopeSpec().isSet()))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005220 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00005221 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005222 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005223 }
Richard Smitha77a0a62011-08-15 21:04:07 +00005224
Richard Smith6331c402012-02-13 22:16:19 +00005225 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005226 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005227 }
5228
Douglas Gregor41866812011-09-12 18:37:38 +00005229 // Set the lexical context. If the declarator has a C++ scope specifier, the
5230 // lexical context will be different from the semantic context.
5231 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005232 if (NewTemplate)
5233 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005234
Richard Smith541b38b2013-09-20 01:15:31 +00005235 if (IsLocalExternDecl)
5236 NewVD->setLocalExternDecl();
5237
Richard Smithb4a9e862013-04-12 22:46:28 +00005238 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005239 if (NewVD->hasLocalStorage()) {
5240 // C++11 [dcl.stc]p4:
5241 // When thread_local is applied to a variable of block scope the
5242 // storage-class-specifier static is implied if it does not appear
5243 // explicitly.
5244 // Core issue: 'static' is not implied if the variable is declared
5245 // 'extern'.
5246 if (SCSpec == DeclSpec::SCS_unspecified &&
5247 TSCS == DeclSpec::TSCS_thread_local &&
5248 DC->isFunctionOrMethod())
5249 NewVD->setTSCSpec(TSCS);
5250 else
5251 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5252 diag::err_thread_non_global)
5253 << DeclSpec::getSpecifierName(TSCS);
5254 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005255 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5256 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005257 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005258 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005259 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005260
John McCallc87d9722013-04-02 02:48:58 +00005261 // C99 6.7.4p3
5262 // An inline definition of a function with external linkage shall
5263 // not contain a definition of a modifiable object with static or
5264 // thread storage duration...
5265 // We only apply this when the function is required to be defined
5266 // elsewhere, i.e. when the function is not 'extern inline'. Note
5267 // that a local variable with thread storage duration still has to
5268 // be marked 'static'. Also note that it's possible to get these
5269 // semantics in C++ using __attribute__((gnu_inline)).
5270 if (SC == SC_Static && S->getFnParent() != 0 &&
5271 !NewVD->getType().isConstQualified()) {
5272 FunctionDecl *CurFD = getCurFunctionDecl();
5273 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5274 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5275 diag::warn_static_local_in_extern_inline);
5276 MaybeSuggestAddingStaticToDecl(CurFD);
5277 }
5278 }
5279
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005280 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005281 if (IsVariableTemplateSpecialization)
5282 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5283 << (IsPartialSpecialization ? 1 : 0)
5284 << FixItHint::CreateRemoval(
5285 D.getDeclSpec().getModulePrivateSpecLoc());
5286 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005287 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5288 << 2
5289 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005290 else if (NewVD->hasLocalStorage())
5291 Diag(NewVD->getLocation(), diag::err_module_private_local)
5292 << 0 << NewVD->getDeclName()
5293 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5294 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005295 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005296 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005297 if (NewTemplate)
5298 NewTemplate->setModulePrivate();
5299 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005300 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005301
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005302 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005303 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005304
Richard Smith848e1f12013-02-01 08:12:08 +00005305 if (NewVD->hasAttrs())
5306 CheckAlignasUnderalignment(NewVD);
5307
Peter Collingbournec6b08572012-08-28 20:37:50 +00005308 if (getLangOpts().CUDA) {
5309 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5310 // storage [duration]."
5311 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005312 (NewVD->hasAttr<CUDASharedAttr>() ||
5313 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005314 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005315 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005316 }
5317
John McCall31168b02011-06-15 23:02:42 +00005318 // In auto-retain/release, infer strong retension for variables of
5319 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005320 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005321 NewVD->setInvalidDecl();
5322
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005323 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005324 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005325 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005326 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005327 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005328 if (S->getFnParent() != 0) {
5329 switch (SC) {
5330 case SC_None:
5331 case SC_Auto:
5332 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5333 break;
5334 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005335 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005336 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5337 break;
5338 case SC_Static:
5339 case SC_Extern:
5340 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005341 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005342 break;
5343 }
5344 }
5345
5346 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005347 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005348 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5349 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5350 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5351 if (I != ExtnameUndeclaredIdentifiers.end()) {
5352 NewVD->addAttr(I->second);
5353 ExtnameUndeclaredIdentifiers.erase(I);
5354 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005355 }
5356
John McCalla2a3f7d2010-03-16 21:48:18 +00005357 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005358 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005359 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005360
John McCall1f82f242009-11-18 22:49:29 +00005361 // Don't consider existing declarations that are in a different
5362 // scope and are out-of-semantic-context declarations (if the new
5363 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005364 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5365 D.getCXXScopeSpec().isNotEmpty() ||
5366 IsExplicitSpecialization ||
5367 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005368
Richard Smith1c34fb72013-08-13 18:18:50 +00005369 // Check whether the previous declaration is in the same block scope. This
5370 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5371 if (getLangOpts().CPlusPlus &&
5372 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5373 NewVD->setPreviousDeclInSameBlockScope(
5374 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005375 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005376
David Blaikiebbafb8a2012-03-11 07:00:24 +00005377 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005378 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5379 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005380 // If this is an explicit specialization of a static data member, check it.
5381 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5382 CheckMemberSpecialization(NewVD, Previous))
5383 NewVD->setInvalidDecl();
5384
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005385 // Merge the decl with the existing one if appropriate.
5386 if (!Previous.empty()) {
5387 if (Previous.isSingleResult() &&
5388 isa<FieldDecl>(Previous.getFoundDecl()) &&
5389 D.getCXXScopeSpec().isSet()) {
5390 // The user tried to define a non-static data member
5391 // out-of-line (C++ [dcl.meaning]p1).
5392 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5393 << D.getCXXScopeSpec().getRange();
5394 Previous.clear();
5395 NewVD->setInvalidDecl();
5396 }
5397 } else if (D.getCXXScopeSpec().isSet()) {
5398 // No previous declaration in the qualifying scope.
5399 Diag(D.getIdentifierLoc(), diag::err_no_member)
5400 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005401 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005402 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005403 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005404
Richard Smithbeef3452014-01-16 23:39:20 +00005405 if (!IsVariableTemplateSpecialization)
5406 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005407
Richard Smithbeef3452014-01-16 23:39:20 +00005408 if (NewTemplate) {
5409 VarTemplateDecl *PrevVarTemplate =
5410 NewVD->getPreviousDecl()
5411 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5412 : 0;
5413
5414 // Check the template parameter list of this declaration, possibly
5415 // merging in the template parameter list from the previous variable
5416 // template declaration.
5417 if (CheckTemplateParameterList(
5418 TemplateParams,
5419 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5420 : 0,
5421 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5422 DC->isDependentContext())
5423 ? TPC_ClassTemplateMember
5424 : TPC_VarTemplate))
5425 NewVD->setInvalidDecl();
5426
5427 // If we are providing an explicit specialization of a static variable
5428 // template, make a note of that.
5429 if (PrevVarTemplate &&
5430 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5431 PrevVarTemplate->setMemberSpecialization();
5432 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005433 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005434
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005435 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005436 checkAttributesAfterMerging(*this, *NewVD);
5437
Richard Smithac974a32013-06-30 09:48:50 +00005438 // If this is the first declaration of an extern C variable, update
5439 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005440 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005441 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005442 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005443
Reid Klecknerd8110b62013-09-10 20:14:30 +00005444 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005445 Decl *ManglingContextDecl;
5446 if (MangleNumberingContext *MCtx =
5447 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5448 ManglingContextDecl)) {
5449 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5450 }
5451 }
5452
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005453 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005454 if (NewVD->isInvalidDecl())
5455 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005456 ActOnDocumentableDecl(NewTemplate);
5457 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005458 }
5459
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005460 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005461}
5462
John McCalldf8b37c2010-03-22 09:20:08 +00005463/// \brief Diagnose variable or built-in function shadowing. Implements
5464/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005465///
John McCalldf8b37c2010-03-22 09:20:08 +00005466/// This method is called whenever a VarDecl is added to a "useful"
5467/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005468///
John McCall2d8c7602010-03-20 04:12:52 +00005469/// \param S the scope in which the shadowing name is being declared
5470/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005471///
John McCalldf8b37c2010-03-22 09:20:08 +00005472void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005473 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005474 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005475 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005476 return;
5477
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005478 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005479 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005480 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005481
5482 DeclContext *NewDC = D->getDeclContext();
5483
John McCall2d8c7602010-03-20 04:12:52 +00005484 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005485 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005486 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005487
John McCalla2a3f7d2010-03-16 21:48:18 +00005488 NamedDecl* ShadowedDecl = R.getFoundDecl();
5489 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5490 return;
5491
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005492 // Fields are not shadowed by variables in C++ static methods.
5493 if (isa<FieldDecl>(ShadowedDecl))
5494 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5495 if (MD->isStatic())
5496 return;
5497
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005498 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5499 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005500 // For shadowing external vars, make sure that we point to the global
5501 // declaration, not a locally scoped extern declaration.
5502 for (VarDecl::redecl_iterator
5503 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5504 I != E; ++I)
5505 if (I->isFileVarDecl()) {
5506 ShadowedDecl = *I;
5507 break;
5508 }
5509 }
5510
5511 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5512
John McCall2d8c7602010-03-20 04:12:52 +00005513 // Only warn about certain kinds of shadowing for class members.
5514 if (NewDC && NewDC->isRecord()) {
5515 // In particular, don't warn about shadowing non-class members.
5516 if (!OldDC->isRecord())
5517 return;
5518
5519 // TODO: should we warn about static data members shadowing
5520 // static data members from base classes?
5521
5522 // TODO: don't diagnose for inaccessible shadowed members.
5523 // This is hard to do perfectly because we might friend the
5524 // shadowing context, but that's just a false negative.
5525 }
5526
5527 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005528 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005529 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005530 if (isa<FieldDecl>(ShadowedDecl))
5531 Kind = 3; // field
5532 else
5533 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005534 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005535 Kind = 1; // global
5536 else
5537 Kind = 0; // local
5538
John McCall2d8c7602010-03-20 04:12:52 +00005539 DeclarationName Name = R.getLookupName();
5540
John McCalla2a3f7d2010-03-16 21:48:18 +00005541 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005542 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5543 return;
John McCall2d8c7602010-03-20 04:12:52 +00005544 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005545 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5546}
5547
John McCalldf8b37c2010-03-22 09:20:08 +00005548/// \brief Check -Wshadow without the advantage of a previous lookup.
5549void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005550 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005551 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005552 return;
5553
John McCalldf8b37c2010-03-22 09:20:08 +00005554 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5555 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5556 LookupName(R, S);
5557 CheckShadow(S, D, R);
5558}
5559
Richard Smithac974a32013-06-30 09:48:50 +00005560/// Check for conflict between this global or extern "C" declaration and
5561/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005562template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005563static bool checkGlobalOrExternCConflict(
5564 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5565 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5566 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005567
Richard Smithac974a32013-06-30 09:48:50 +00005568 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5569 // The common case: this global doesn't conflict with any extern "C"
5570 // declaration.
5571 return false;
5572 }
5573
5574 if (Prev) {
5575 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5576 // Both the old and new declarations have C language linkage. This is a
5577 // redeclaration.
5578 Previous.clear();
5579 Previous.addDecl(Prev);
5580 return true;
5581 }
5582
5583 // This is a global, non-extern "C" declaration, and there is a previous
5584 // non-global extern "C" declaration. Diagnose if this is a variable
5585 // declaration.
5586 if (!isa<VarDecl>(ND))
5587 return false;
5588 } else {
5589 // The declaration is extern "C". Check for any declaration in the
5590 // translation unit which might conflict.
5591 if (IsGlobal) {
5592 // We have already performed the lookup into the translation unit.
5593 IsGlobal = false;
5594 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5595 I != E; ++I) {
5596 if (isa<VarDecl>(*I)) {
5597 Prev = *I;
5598 break;
5599 }
5600 }
5601 } else {
5602 DeclContext::lookup_result R =
5603 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5604 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5605 I != E; ++I) {
5606 if (isa<VarDecl>(*I)) {
5607 Prev = *I;
5608 break;
5609 }
5610 // FIXME: If we have any other entity with this name in global scope,
5611 // the declaration is ill-formed, but that is a defect: it breaks the
5612 // 'stat' hack, for instance. Only variables can have mangled name
5613 // clashes with extern "C" declarations, so only they deserve a
5614 // diagnostic.
5615 }
5616 }
5617
5618 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005619 return false;
5620 }
5621
Richard Smithac974a32013-06-30 09:48:50 +00005622 // Use the first declaration's location to ensure we point at something which
5623 // is lexically inside an extern "C" linkage-spec.
5624 assert(Prev && "should have found a previous declaration to diagnose");
5625 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005626 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005627 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005628 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005629
5630 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5631 << IsGlobal << ND;
5632 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5633 << IsGlobal;
5634 return false;
5635}
5636
5637/// Apply special rules for handling extern "C" declarations. Returns \c true
5638/// if we have found that this is a redeclaration of some prior entity.
5639///
5640/// Per C++ [dcl.link]p6:
5641/// Two declarations [for a function or variable] with C language linkage
5642/// with the same name that appear in different scopes refer to the same
5643/// [entity]. An entity with C language linkage shall not be declared with
5644/// the same name as an entity in global scope.
5645template<typename T>
5646static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5647 LookupResult &Previous) {
5648 if (!S.getLangOpts().CPlusPlus) {
5649 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005650 // variable declared in function scope. We don't need this in C++, because
5651 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005652 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5653 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5654 Previous.clear();
5655 Previous.addDecl(Prev);
5656 return true;
5657 }
5658 }
5659 return false;
5660 }
5661
5662 // A declaration in the translation unit can conflict with an extern "C"
5663 // declaration.
5664 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5665 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5666
5667 // An extern "C" declaration can conflict with a declaration in the
5668 // translation unit or can be a redeclaration of an extern "C" declaration
5669 // in another scope.
5670 if (isIncompleteDeclExternC(S,ND))
5671 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5672
5673 // Neither global nor extern "C": nothing to do.
5674 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005675}
5676
Richard Smith27d807c2013-04-30 13:56:41 +00005677void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005678 // If the decl is already known invalid, don't check it.
5679 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005680 return;
Mike Stump11289f42009-09-09 15:08:12 +00005681
Abramo Bagnara341ab732012-11-08 14:44:42 +00005682 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5683 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005684
Richard Smith27d807c2013-04-30 13:56:41 +00005685 // Defer checking an 'auto' type until its initializer is attached.
5686 if (T->isUndeducedType())
5687 return;
5688
John McCall8b07ec22010-05-15 11:32:37 +00005689 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005690 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5691 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005692 T = Context.getObjCObjectPointerType(T);
5693 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005694 }
Mike Stump11289f42009-09-09 15:08:12 +00005695
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005696 // Emit an error if an address space was applied to decl with local storage.
5697 // This includes arrays of objects with address space qualifiers, but not
5698 // automatic variables that point to other address spaces.
5699 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005700 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005701 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005702 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005703 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005704 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005705
Tanya Lattner713eef42013-04-05 20:14:50 +00005706 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5707 // __constant address space.
5708 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5709 && T.getAddressSpace() != LangAS::opencl_constant
5710 && !T->isSamplerT()){
5711 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5712 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005713 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005714 }
5715
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005716 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5717 // scope.
5718 if ((getLangOpts().OpenCLVersion >= 120)
5719 && NewVD->isStaticLocal()) {
5720 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5721 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005722 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005723 }
5724
Mike Stumpca5ae662009-04-14 00:57:29 +00005725 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005726 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005727 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005728 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005729 else {
5730 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005731 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005732 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005733 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005734
Chris Lattner9fecd742009-04-19 05:21:20 +00005735 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005736 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005737 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005738 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005739
Chris Lattner9fecd742009-04-19 05:21:20 +00005740 if ((isVM && NewVD->hasLinkage()) ||
5741 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005742 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005743 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005744 TypeSourceInfo *FixedTInfo =
5745 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5746 SizeIsNegative, Oversized);
5747 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005748 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005749 // FIXME: This won't give the correct result for
5750 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005751 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005752
Anders Carlsson6c885802009-02-28 21:56:50 +00005753 if (NewVD->isFileVarDecl())
5754 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005755 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005756 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005757 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005758 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005759 else
5760 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005761 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005762 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005763 return;
Mike Stump11289f42009-09-09 15:08:12 +00005764 }
5765
Abramo Bagnara341ab732012-11-08 14:44:42 +00005766 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005767 if (NewVD->isFileVarDecl())
5768 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5769 else
5770 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005771 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005772 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005773 }
Mike Stump11289f42009-09-09 15:08:12 +00005774
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005775 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005776 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005777 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005778 }
5779
David Majnemer0ffa3312013-05-29 00:56:45 +00005780 if (T->isVoidType()) {
5781 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5782 // of objects and functions.
5783 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5784 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5785 << T;
5786 NewVD->setInvalidDecl();
5787 return;
5788 }
Richard Smith27d807c2013-04-30 13:56:41 +00005789 }
5790
5791 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5792 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5793 NewVD->setInvalidDecl();
5794 return;
5795 }
5796
5797 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5798 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5799 NewVD->setInvalidDecl();
5800 return;
5801 }
5802
5803 if (NewVD->isConstexpr() && !T->isDependentType() &&
5804 RequireLiteralType(NewVD->getLocation(), T,
5805 diag::err_constexpr_var_non_literal)) {
5806 // Can't perform this check until the type is deduced.
5807 NewVD->setInvalidDecl();
5808 return;
5809 }
5810}
5811
5812/// \brief Perform semantic checking on a newly-created variable
5813/// declaration.
5814///
5815/// This routine performs all of the type-checking required for a
5816/// variable declaration once it has been built. It is used both to
5817/// check variables after they have been parsed and their declarators
5818/// have been translated into a declaration, and to check variables
5819/// that have been instantiated from a template.
5820///
5821/// Sets NewVD->isInvalidDecl() if an error was encountered.
5822///
5823/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005824bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005825 CheckVariableDeclarationType(NewVD);
5826
5827 // If the decl is already known invalid, don't check it.
5828 if (NewVD->isInvalidDecl())
5829 return false;
5830
John McCallb65e8fe2013-04-01 18:34:28 +00005831 // If we did not find anything by this name, look for a non-visible
5832 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005833 if (Previous.empty() &&
5834 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005835 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005836
Douglas Gregor3552dab2013-01-09 00:47:56 +00005837 // Filter out any non-conflicting previous declarations.
5838 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5839
John McCall1f82f242009-11-18 22:49:29 +00005840 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005841 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005842 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005843 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005844 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005845}
5846
Douglas Gregor36d1b142009-10-06 17:59:45 +00005847/// \brief Data used with FindOverriddenMethod
5848struct FindOverriddenMethodData {
5849 Sema *S;
5850 CXXMethodDecl *Method;
5851};
5852
5853/// \brief Member lookup function that determines whether a given C++
5854/// method overrides a method in a base class, to be used with
5855/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005856static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005857 CXXBasePath &Path,
5858 void *UserData) {
5859 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005860
Douglas Gregor36d1b142009-10-06 17:59:45 +00005861 FindOverriddenMethodData *Data
5862 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005863
5864 DeclarationName Name = Data->Method->getDeclName();
5865
5866 // FIXME: Do we care about other names here too?
5867 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005868 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005869 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5870 CanQualType CT = Data->S->Context.getCanonicalType(T);
5871
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005872 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005873 }
5874
5875 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005876 !Path.Decls.empty();
5877 Path.Decls = Path.Decls.slice(1)) {
5878 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005879 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5880 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005881 return true;
5882 }
5883 }
5884
5885 return false;
5886}
5887
David Blaikie7e414262012-10-17 00:47:58 +00005888namespace {
5889 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5890}
5891/// \brief Report an error regarding overriding, along with any relevant
5892/// overriden methods.
5893///
5894/// \param DiagID the primary error to report.
5895/// \param MD the overriding method.
5896/// \param OEK which overrides to include as notes.
5897static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5898 OverrideErrorKind OEK = OEK_All) {
5899 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5900 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5901 E = MD->end_overridden_methods();
5902 I != E; ++I) {
5903 // This check (& the OEK parameter) could be replaced by a predicate, but
5904 // without lambdas that would be overkill. This is still nicer than writing
5905 // out the diag loop 3 times.
5906 if ((OEK == OEK_All) ||
5907 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5908 (OEK == OEK_Deleted && (*I)->isDeleted()))
5909 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5910 }
5911}
5912
Sebastian Redld5b24532009-11-18 21:51:29 +00005913/// AddOverriddenMethods - See if a method overrides any in the base classes,
5914/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005915bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00005916 // Look for virtual methods in base classes that this method might override.
5917 CXXBasePaths Paths;
5918 FindOverriddenMethodData Data;
5919 Data.Method = MD;
5920 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00005921 bool hasDeletedOverridenMethods = false;
5922 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005923 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00005924 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5925 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5926 E = Paths.found_decls_end(); I != E; ++I) {
5927 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00005928 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00005929 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00005930 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00005931 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00005932 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00005933 hasDeletedOverridenMethods |= OldMD->isDeleted();
5934 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005935 AddedAny = true;
5936 }
Sebastian Redld5b24532009-11-18 21:51:29 +00005937 }
5938 }
5939 }
David Blaikie7e414262012-10-17 00:47:58 +00005940
5941 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5942 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5943 }
5944 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5945 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5946 }
5947
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005948 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00005949}
5950
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005951namespace {
5952 // Struct for holding all of the extra arguments needed by
5953 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5954 struct ActOnFDArgs {
5955 Scope *S;
5956 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005957 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005958 bool AddToScope;
5959 };
5960}
5961
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005962namespace {
5963
5964// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005965// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005966class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5967 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005968 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5969 CXXRecordDecl *Parent)
5970 : Context(Context), OriginalFD(TypoFD),
5971 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005972
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005973 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005974 if (candidate.getEditDistance() == 0)
5975 return false;
5976
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005977 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005978 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5979 CDeclEnd = candidate.end();
5980 CDecl != CDeclEnd; ++CDecl) {
5981 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5982
5983 if (FD && !FD->hasBody() &&
5984 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
5985 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5986 CXXRecordDecl *Parent = MD->getParent();
5987 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
5988 return true;
5989 } else if (!ExpectedParent) {
5990 return true;
5991 }
5992 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005993 }
5994
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005995 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005996 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005997
5998 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005999 ASTContext &Context;
6000 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006001 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006002};
6003
6004}
6005
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006006/// \brief Generate diagnostics for an invalid function redeclaration.
6007///
6008/// This routine handles generating the diagnostic messages for an invalid
6009/// function redeclaration, including finding possible similar declarations
6010/// or performing typo correction if there are no previous declarations with
6011/// the same name.
6012///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006013/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006014/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006015static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006016 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006017 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006018 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006019 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006020 SmallVector<unsigned, 1> MismatchedParams;
6021 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006022 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006023 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006024 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6025 : diag::err_member_decl_does_not_match;
6026 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6027 IsLocalFriend ? Sema::LookupLocalFriendName
6028 : Sema::LookupOrdinaryName,
6029 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006030
6031 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006032 if (IsLocalFriend)
6033 SemaRef.LookupName(Prev, S);
6034 else
6035 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006036 assert(!Prev.isAmbiguous() &&
6037 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006038 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006039 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6040 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006041 if (!Prev.empty()) {
6042 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6043 Func != FuncEnd; ++Func) {
6044 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006045 if (FD &&
6046 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006047 // Add 1 to the index so that 0 can mean the mismatch didn't
6048 // involve a parameter
6049 unsigned ParamNum =
6050 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6051 NearMatches.push_back(std::make_pair(FD, ParamNum));
6052 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006053 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006054 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006055 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006056 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6057 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6058 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006059 // Set up everything for the call to ActOnFunctionDeclarator
6060 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6061 ExtraArgs.D.getIdentifierLoc());
6062 Previous.clear();
6063 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006064 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6065 CDeclEnd = Correction.end();
6066 CDecl != CDeclEnd; ++CDecl) {
6067 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006068 if (FD && !FD->hasBody() &&
6069 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006070 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006071 }
6072 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006073 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006074
6075 NamedDecl *Result;
6076 // Retry building the function declaration with the new previous
6077 // declarations, and with errors suppressed.
6078 {
6079 // Trap errors.
6080 Sema::SFINAETrap Trap(SemaRef);
6081
6082 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6083 // pieces need to verify the typo-corrected C++ declaration and hopefully
6084 // eliminate the need for the parameter pack ExtraArgs.
6085 Result = SemaRef.ActOnFunctionDeclarator(
6086 ExtraArgs.S, ExtraArgs.D,
6087 Correction.getCorrectionDecl()->getDeclContext(),
6088 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6089 ExtraArgs.AddToScope);
6090
6091 if (Trap.hasErrorOccurred())
6092 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006093 }
Richard Smithf9b15102013-08-17 00:46:16 +00006094
6095 if (Result) {
6096 // Determine which correction we picked.
6097 Decl *Canonical = Result->getCanonicalDecl();
6098 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6099 I != E; ++I)
6100 if ((*I)->getCanonicalDecl() == Canonical)
6101 Correction.setCorrectionDecl(*I);
6102
6103 SemaRef.diagnoseTypo(
6104 Correction,
6105 SemaRef.PDiag(IsLocalFriend
6106 ? diag::err_no_matching_local_friend_suggest
6107 : diag::err_member_decl_does_not_match_suggest)
6108 << Name << NewDC << IsDefinition);
6109 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006110 }
Richard Smithf9b15102013-08-17 00:46:16 +00006111
6112 // Pretend the typo correction never occurred
6113 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6114 ExtraArgs.D.getIdentifierLoc());
6115 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6116 Previous.clear();
6117 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006118 }
6119
Richard Smithf9b15102013-08-17 00:46:16 +00006120 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6121 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006122
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006123 bool NewFDisConst = false;
6124 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006125 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006126
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006127 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006128 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6129 NearMatch != NearMatchEnd; ++NearMatch) {
6130 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006131 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6132 bool FDisConst = MD && MD->isConst();
6133 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006134
Richard Smith541b38b2013-09-20 01:15:31 +00006135 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006136 if (unsigned Idx = NearMatch->second) {
6137 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006138 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6139 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006140 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6141 : diag::note_local_decl_close_param_match)
6142 << Idx << FDParam->getType()
6143 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006144 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006145 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006146 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006147 } else
Richard Smith114394f2013-08-09 04:35:01 +00006148 SemaRef.Diag(FD->getLocation(),
6149 IsMember ? diag::note_member_def_close_match
6150 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006151 }
Richard Smithf9b15102013-08-17 00:46:16 +00006152 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006153}
6154
David Blaikie30d15442011-10-19 22:56:21 +00006155static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6156 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006157 switch (D.getDeclSpec().getStorageClassSpec()) {
6158 default: llvm_unreachable("Unknown storage class!");
6159 case DeclSpec::SCS_auto:
6160 case DeclSpec::SCS_register:
6161 case DeclSpec::SCS_mutable:
6162 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6163 diag::err_typecheck_sclass_func);
6164 D.setInvalidType();
6165 break;
6166 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006167 case DeclSpec::SCS_extern:
6168 if (D.getDeclSpec().isExternInLinkageSpec())
6169 return SC_None;
6170 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006171 case DeclSpec::SCS_static: {
6172 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6173 // C99 6.7.1p5:
6174 // The declaration of an identifier for a function that has
6175 // block scope shall have no explicit storage-class specifier
6176 // other than extern
6177 // See also (C++ [dcl.stc]p4).
6178 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6179 diag::err_static_block_func);
6180 break;
6181 } else
6182 return SC_Static;
6183 }
6184 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6185 }
6186
6187 // No explicit storage class has already been returned
6188 return SC_None;
6189}
6190
6191static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6192 DeclContext *DC, QualType &R,
6193 TypeSourceInfo *TInfo,
6194 FunctionDecl::StorageClass SC,
6195 bool &IsVirtualOkay) {
6196 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6197 DeclarationName Name = NameInfo.getName();
6198
6199 FunctionDecl *NewFD = 0;
6200 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006201
David Blaikiebbafb8a2012-03-11 07:00:24 +00006202 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006203 // Determine whether the function was written with a
6204 // prototype. This true when:
6205 // - there is a prototype in the declarator, or
6206 // - the type R of the function is some kind of typedef or other reference
6207 // to a type name (which eventually refers to a function type).
6208 bool HasPrototype =
6209 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6210 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6211
David Blaikie30d15442011-10-19 22:56:21 +00006212 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006213 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006214 TInfo, SC, isInline,
6215 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006216 if (D.isInvalidType())
6217 NewFD->setInvalidDecl();
6218
6219 // Set the lexical context.
6220 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6221
6222 return NewFD;
6223 }
6224
6225 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6226 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6227
6228 // Check that the return type is not an abstract class type.
6229 // For record types, this is done by the AbstractClassUsageDiagnoser once
6230 // the class has been completely parsed.
6231 if (!DC->isRecord() &&
6232 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6233 R->getAs<FunctionType>()->getResultType(),
6234 diag::err_abstract_type_in_decl,
6235 SemaRef.AbstractReturnType))
6236 D.setInvalidType();
6237
6238 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6239 // This is a C++ constructor declaration.
6240 assert(DC->isRecord() &&
6241 "Constructors can only be declared in a member context");
6242
6243 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6244 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006245 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006246 R, TInfo, isExplicit, isInline,
6247 /*isImplicitlyDeclared=*/false,
6248 isConstexpr);
6249
6250 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6251 // This is a C++ destructor declaration.
6252 if (DC->isRecord()) {
6253 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6254 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6255 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6256 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006257 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006258 NameInfo, R, TInfo, isInline,
6259 /*isImplicitlyDeclared=*/false);
6260
6261 // If the class is complete, then we now create the implicit exception
6262 // specification. If the class is incomplete or dependent, we can't do
6263 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006264 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006265 Record->getDefinition() && !Record->isBeingDefined() &&
6266 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6267 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6268 }
6269
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006270 // The Microsoft ABI requires that we perform the destructor body
6271 // checks (i.e. operator delete() lookup) at every declaration, as
6272 // any translation unit may need to emit a deleting destructor.
6273 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6274 !Record->isDependentType() && Record->getDefinition() &&
Hans Wennborge955e392013-12-17 17:49:22 +00006275 !Record->isBeingDefined() && !NewDD->isDeleted()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006276 SemaRef.CheckDestructor(NewDD);
6277 }
6278
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006279 IsVirtualOkay = true;
6280 return NewDD;
6281
6282 } else {
6283 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6284 D.setInvalidType();
6285
6286 // Create a FunctionDecl to satisfy the function definition parsing
6287 // code path.
6288 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006289 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006290 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006291 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006292 /*hasPrototype=*/true, isConstexpr);
6293 }
6294
6295 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6296 if (!DC->isRecord()) {
6297 SemaRef.Diag(D.getIdentifierLoc(),
6298 diag::err_conv_function_not_member);
6299 return 0;
6300 }
6301
6302 SemaRef.CheckConversionDeclarator(D, R, SC);
6303 IsVirtualOkay = true;
6304 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006305 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006306 R, TInfo, isInline, isExplicit,
6307 isConstexpr, SourceLocation());
6308
6309 } else if (DC->isRecord()) {
6310 // If the name of the function is the same as the name of the record,
6311 // then this must be an invalid constructor that has a return type.
6312 // (The parser checks for a return type and makes the declarator a
6313 // constructor if it has no return type).
6314 if (Name.getAsIdentifierInfo() &&
6315 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6316 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6317 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6318 << SourceRange(D.getIdentifierLoc());
6319 return 0;
6320 }
6321
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006322 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006323 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6324 cast<CXXRecordDecl>(DC),
6325 D.getLocStart(), NameInfo, R,
6326 TInfo, SC, isInline,
6327 isConstexpr, SourceLocation());
6328 IsVirtualOkay = !Ret->isStatic();
6329 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006330 } else {
6331 // Determine whether the function was written with a
6332 // prototype. This true when:
6333 // - we're in C++ (where every function has a prototype),
6334 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006335 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006336 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006337 true/*HasPrototype*/, isConstexpr);
6338 }
6339}
6340
Eli Friedman8f5e9832012-09-20 01:40:23 +00006341void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6342 // In C++, the empty parameter-type-list must be spelled "void"; a
6343 // typedef of void is not permitted.
6344 if (getLangOpts().CPlusPlus &&
6345 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6346 bool IsTypeAlias = false;
6347 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6348 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6349 else if (const TemplateSpecializationType *TST =
6350 Param->getType()->getAs<TemplateSpecializationType>())
6351 IsTypeAlias = TST->isTypeAlias();
6352 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6353 << IsTypeAlias;
6354 }
6355}
6356
Matt Arsenaultefb38192013-07-23 01:23:36 +00006357enum OpenCLParamType {
6358 ValidKernelParam,
6359 PtrPtrKernelParam,
6360 PtrKernelParam,
6361 InvalidKernelParam,
6362 RecordKernelParam
6363};
6364
6365static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6366 if (PT->isPointerType()) {
6367 QualType PointeeType = PT->getPointeeType();
6368 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6369 }
6370
6371 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6372 // be used as builtin types.
6373
6374 if (PT->isImageType())
6375 return PtrKernelParam;
6376
6377 if (PT->isBooleanType())
6378 return InvalidKernelParam;
6379
6380 if (PT->isEventT())
6381 return InvalidKernelParam;
6382
6383 if (PT->isHalfType())
6384 return InvalidKernelParam;
6385
6386 if (PT->isRecordType())
6387 return RecordKernelParam;
6388
6389 return ValidKernelParam;
6390}
6391
6392static void checkIsValidOpenCLKernelParameter(
6393 Sema &S,
6394 Declarator &D,
6395 ParmVarDecl *Param,
6396 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6397 QualType PT = Param->getType();
6398
6399 // Cache the valid types we encounter to avoid rechecking structs that are
6400 // used again
6401 if (ValidTypes.count(PT.getTypePtr()))
6402 return;
6403
6404 switch (getOpenCLKernelParameterType(PT)) {
6405 case PtrPtrKernelParam:
6406 // OpenCL v1.2 s6.9.a:
6407 // A kernel function argument cannot be declared as a
6408 // pointer to a pointer type.
6409 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6410 D.setInvalidType();
6411 return;
6412
6413 // OpenCL v1.2 s6.9.k:
6414 // Arguments to kernel functions in a program cannot be declared with the
6415 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6416 // uintptr_t or a struct and/or union that contain fields declared to be
6417 // one of these built-in scalar types.
6418
6419 case InvalidKernelParam:
6420 // OpenCL v1.2 s6.8 n:
6421 // A kernel function argument cannot be declared
6422 // of event_t type.
6423 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6424 D.setInvalidType();
6425 return;
6426
6427 case PtrKernelParam:
6428 case ValidKernelParam:
6429 ValidTypes.insert(PT.getTypePtr());
6430 return;
6431
6432 case RecordKernelParam:
6433 break;
6434 }
6435
6436 // Track nested structs we will inspect
6437 SmallVector<const Decl *, 4> VisitStack;
6438
6439 // Track where we are in the nested structs. Items will migrate from
6440 // VisitStack to HistoryStack as we do the DFS for bad field.
6441 SmallVector<const FieldDecl *, 4> HistoryStack;
6442 HistoryStack.push_back((const FieldDecl *) 0);
6443
6444 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6445 VisitStack.push_back(PD);
6446
6447 assert(VisitStack.back() && "First decl null?");
6448
6449 do {
6450 const Decl *Next = VisitStack.pop_back_val();
6451 if (!Next) {
6452 assert(!HistoryStack.empty());
6453 // Found a marker, we have gone up a level
6454 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6455 ValidTypes.insert(Hist->getType().getTypePtr());
6456
6457 continue;
6458 }
6459
6460 // Adds everything except the original parameter declaration (which is not a
6461 // field itself) to the history stack.
6462 const RecordDecl *RD;
6463 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6464 HistoryStack.push_back(Field);
6465 RD = Field->getType()->castAs<RecordType>()->getDecl();
6466 } else {
6467 RD = cast<RecordDecl>(Next);
6468 }
6469
6470 // Add a null marker so we know when we've gone back up a level
6471 VisitStack.push_back((const Decl *) 0);
6472
6473 for (RecordDecl::field_iterator I = RD->field_begin(),
6474 E = RD->field_end(); I != E; ++I) {
6475 const FieldDecl *FD = *I;
6476 QualType QT = FD->getType();
6477
6478 if (ValidTypes.count(QT.getTypePtr()))
6479 continue;
6480
6481 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6482 if (ParamType == ValidKernelParam)
6483 continue;
6484
6485 if (ParamType == RecordKernelParam) {
6486 VisitStack.push_back(FD);
6487 continue;
6488 }
6489
6490 // OpenCL v1.2 s6.9.p:
6491 // Arguments to kernel functions that are declared to be a struct or union
6492 // do not allow OpenCL objects to be passed as elements of the struct or
6493 // union.
6494 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6495 S.Diag(Param->getLocation(),
6496 diag::err_record_with_pointers_kernel_param)
6497 << PT->isUnionType()
6498 << PT;
6499 } else {
6500 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6501 }
6502
6503 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6504 << PD->getDeclName();
6505
6506 // We have an error, now let's go back up through history and show where
6507 // the offending field came from
6508 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6509 E = HistoryStack.end(); I != E; ++I) {
6510 const FieldDecl *OuterField = *I;
6511 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6512 << OuterField->getType();
6513 }
6514
6515 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6516 << QT->isPointerType()
6517 << QT;
6518 D.setInvalidType();
6519 return;
6520 }
6521 } while (!VisitStack.empty());
6522}
6523
Mike Stump11289f42009-09-09 15:08:12 +00006524NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006525Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006526 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006527 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006528 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006529 QualType R = TInfo->getType();
6530
Zhongxing Xubece5d62009-01-16 01:13:29 +00006531 assert(R.getTypePtr()->isFunctionType());
6532
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006533 // TODO: consider using NameInfo for diagnostic.
6534 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6535 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006536 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006537
Richard Smithb4a9e862013-04-12 22:46:28 +00006538 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6539 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6540 diag::err_invalid_thread)
6541 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006542
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006543 if (D.isFirstDeclarationOfMember())
6544 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006545
Douglas Gregor513e63c2010-12-10 19:28:19 +00006546 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006547 FunctionTemplateDecl *FunctionTemplate = 0;
6548 bool isExplicitSpecialization = false;
6549 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006550
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006551 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006552 bool HasExplicitTemplateArgs = false;
6553 TemplateArgumentListInfo TemplateArgs;
6554
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006555 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006556
Richard Smith541b38b2013-09-20 01:15:31 +00006557 DeclContext *OriginalDC = DC;
6558 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6559
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006560 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6561 isVirtualOkay);
6562 if (!NewFD) return 0;
6563
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006564 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6565 NewFD->setTopLevelDeclInObjCContainer();
6566
Richard Smith541b38b2013-09-20 01:15:31 +00006567 // Set the lexical context. If this is a function-scope declaration, or has a
6568 // C++ scope specifier, or is the object of a friend declaration, the lexical
6569 // context will be different from the semantic context.
6570 NewFD->setLexicalDeclContext(CurContext);
6571
6572 if (IsLocalExternDecl)
6573 NewFD->setLocalExternDecl();
6574
David Blaikiebbafb8a2012-03-11 07:00:24 +00006575 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006576 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006577 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6578 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006579 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006580 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006581 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006582 // C++ [class.friend]p5
6583 // A function can be defined in a friend declaration of a
6584 // class . . . . Such a function is implicitly inline.
6585 NewFD->setImplicitlyInline();
6586 }
6587
John McCalldb632ac2012-09-25 07:32:39 +00006588 // If this is a method defined in an __interface, and is not a constructor
6589 // or an overloaded operator, then set the pure flag (isVirtual will already
6590 // return true).
6591 if (const CXXRecordDecl *Parent =
6592 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6593 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006594 NewFD->setPure(true);
6595 }
6596
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006597 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006598 isExplicitSpecialization = false;
6599 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006600 if (D.isInvalidType())
6601 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006602
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006603 // Match up the template parameter lists with the scope specifier, then
6604 // determine whether we have a template or a template specialization.
6605 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006606 if (TemplateParameterList *TemplateParams =
6607 MatchTemplateParametersToScopeSpecifier(
6608 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6609 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6610 isExplicitSpecialization, Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006611 if (TemplateParams->size() > 0) {
6612 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006613
Abramo Bagnara60804e12011-03-18 15:16:37 +00006614 // Check that we can declare a template here.
6615 if (CheckTemplateDeclScope(S, TemplateParams))
6616 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006617
Abramo Bagnara60804e12011-03-18 15:16:37 +00006618 // A destructor cannot be a template.
6619 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6620 Diag(NewFD->getLocation(), diag::err_destructor_template);
6621 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006622 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006623
6624 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006625 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006626 // now that we know what the current instantiation is.
6627 if (DC->isDependentContext()) {
6628 ContextRAII SavedContext(*this, DC);
6629 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6630 Invalid = true;
6631 }
6632
John McCall1f0479e2010-03-24 08:27:58 +00006633
Abramo Bagnara60804e12011-03-18 15:16:37 +00006634 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6635 NewFD->getLocation(),
6636 Name, TemplateParams,
6637 NewFD);
6638 FunctionTemplate->setLexicalDeclContext(CurContext);
6639 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6640
6641 // For source fidelity, store the other template param lists.
6642 if (TemplateParamLists.size() > 1) {
6643 NewFD->setTemplateParameterListsInfo(Context,
6644 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006645 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006646 }
6647 } else {
6648 // This is a function template specialization.
6649 isFunctionTemplateSpecialization = true;
6650 // For source fidelity, store all the template param lists.
6651 NewFD->setTemplateParameterListsInfo(Context,
6652 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006653 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006654
6655 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6656 if (isFriend) {
6657 // We want to remove the "template<>", found here.
6658 SourceRange RemoveRange = TemplateParams->getSourceRange();
6659
6660 // If we remove the template<> and the name is not a
6661 // template-id, we're actually silently creating a problem:
6662 // the friend declaration will refer to an untemplated decl,
6663 // and clearly the user wants a template specialization. So
6664 // we need to insert '<>' after the name.
6665 SourceLocation InsertLoc;
6666 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6667 InsertLoc = D.getName().getSourceRange().getEnd();
6668 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6669 }
6670
6671 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6672 << Name << RemoveRange
6673 << FixItHint::CreateRemoval(RemoveRange)
6674 << FixItHint::CreateInsertion(InsertLoc, "<>");
6675 }
6676 }
6677 }
6678 else {
6679 // All template param lists were matched against the scope specifier:
6680 // this is NOT (an explicit specialization of) a template.
6681 if (TemplateParamLists.size() > 0)
6682 // For source fidelity, store all the template param lists.
6683 NewFD->setTemplateParameterListsInfo(Context,
6684 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006685 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006686 }
6687
6688 if (Invalid) {
6689 NewFD->setInvalidDecl();
6690 if (FunctionTemplate)
6691 FunctionTemplate->setInvalidDecl();
6692 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006693
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006694 // C++ [dcl.fct.spec]p5:
6695 // The virtual specifier shall only be used in declarations of
6696 // nonstatic class member functions that appear within a
6697 // member-specification of a class declaration; see 10.3.
6698 //
6699 if (isVirtual && !NewFD->isInvalidDecl()) {
6700 if (!isVirtualOkay) {
6701 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6702 diag::err_virtual_non_function);
6703 } else if (!CurContext->isRecord()) {
6704 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006705 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6706 diag::err_virtual_out_of_class)
6707 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6708 } else if (NewFD->getDescribedFunctionTemplate()) {
6709 // C++ [temp.mem]p3:
6710 // A member function template shall not be virtual.
6711 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6712 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006713 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6714 } else {
6715 // Okay: Add virtual to the method.
6716 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006717 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006718
6719 if (getLangOpts().CPlusPlus1y &&
6720 NewFD->getResultType()->isUndeducedType())
6721 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006722 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006723
Richard Smithc1564702013-11-15 02:58:23 +00006724 if (getLangOpts().CPlusPlus1y &&
6725 (NewFD->isDependentContext() ||
6726 (isFriend && CurContext->isDependentContext())) &&
Richard Smithc58f38f2013-08-14 20:16:31 +00006727 NewFD->getResultType()->isUndeducedType()) {
6728 // If the function template is referenced directly (for instance, as a
6729 // member of the current instantiation), pretend it has a dependent type.
6730 // This is not really justified by the standard, but is the only sane
6731 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006732 // FIXME: For a friend function, we have not marked the function as being
6733 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006734 const FunctionProtoType *FPT =
6735 NewFD->getType()->castAs<FunctionProtoType>();
6736 QualType Result = SubstAutoType(FPT->getResultType(),
6737 Context.DependentTy);
6738 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6739 FPT->getExtProtoInfo()));
6740 }
6741
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006742 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006743 // The inline specifier shall not appear on a block scope function
6744 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006745 if (isInline && !NewFD->isInvalidDecl()) {
6746 if (CurContext->isFunctionOrMethod()) {
6747 // 'inline' is not allowed on block scope function declaration.
6748 Diag(D.getDeclSpec().getInlineSpecLoc(),
6749 diag::err_inline_declaration_block_scope) << Name
6750 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6751 }
6752 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006753
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006754 // C++ [dcl.fct.spec]p6:
6755 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006756 // constructor or conversion function within its class definition;
6757 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006758 if (isExplicit && !NewFD->isInvalidDecl()) {
6759 if (!CurContext->isRecord()) {
6760 // 'explicit' was specified outside of the class.
6761 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6762 diag::err_explicit_out_of_class)
6763 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6764 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6765 !isa<CXXConversionDecl>(NewFD)) {
6766 // 'explicit' was specified on a function that wasn't a constructor
6767 // or conversion function.
6768 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6769 diag::err_explicit_non_ctor_or_conv_function)
6770 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6771 }
6772 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006773
Richard Smitha77a0a62011-08-15 21:04:07 +00006774 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006775 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006776 // are implicitly inline.
6777 NewFD->setImplicitlyInline();
6778
Richard Smith574f4f62013-01-14 05:37:29 +00006779 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006780 // be either constructors or to return a literal type. Therefore,
6781 // destructors cannot be declared constexpr.
6782 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006783 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006784 }
6785
Douglas Gregor26701a42011-09-09 02:06:17 +00006786 // If __module_private__ was specified, mark the function accordingly.
6787 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006788 if (isFunctionTemplateSpecialization) {
6789 SourceLocation ModulePrivateLoc
6790 = D.getDeclSpec().getModulePrivateSpecLoc();
6791 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6792 << 0
6793 << FixItHint::CreateRemoval(ModulePrivateLoc);
6794 } else {
6795 NewFD->setModulePrivate();
6796 if (FunctionTemplate)
6797 FunctionTemplate->setModulePrivate();
6798 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006799 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006800
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006801 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006802 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006803 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006804 FunctionTemplate->setAccess(AS_public);
6805 }
Richard Smith64017682013-07-17 23:53:16 +00006806 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006807 NewFD->setAccess(AS_public);
6808 }
6809
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006810 // If a function is defined as defaulted or deleted, mark it as such now.
6811 switch (D.getFunctionDefinitionKind()) {
6812 case FDK_Declaration:
6813 case FDK_Definition:
6814 break;
6815
6816 case FDK_Defaulted:
6817 NewFD->setDefaulted();
6818 break;
6819
6820 case FDK_Deleted:
6821 NewFD->setDeletedAsWritten();
6822 break;
6823 }
6824
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006825 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6826 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006827 // C++ [class.mfct]p2:
6828 // A member function may be defined (8.4) in its class definition, in
6829 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006830 NewFD->setImplicitlyInline();
6831 }
6832
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006833 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6834 !CurContext->isRecord()) {
6835 // C++ [class.static]p1:
6836 // A data or function member of a class may be declared static
6837 // in a class definition, in which case it is a static member of
6838 // the class.
6839
6840 // Complain about the 'static' specifier if it's on an out-of-line
6841 // member function definition.
6842 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6843 diag::err_static_out_of_line)
6844 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6845 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006846
6847 // C++11 [except.spec]p15:
6848 // A deallocation function with no exception-specification is treated
6849 // as if it were specified with noexcept(true).
6850 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6851 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6852 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006853 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006854 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6855 EPI.ExceptionSpecType = EST_BasicNoexcept;
6856 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00006857 FPT->getArgTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006858 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006859 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006860
6861 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006862 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00006863 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006864 isExplicitSpecialization ||
6865 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006866
Zhongxing Xubece5d62009-01-16 01:13:29 +00006867 // Handle GNU asm-label extension (encoded as an attribute).
6868 if (Expr *E = (Expr*) D.getAsmLabel()) {
6869 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006870 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006871 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00006872 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00006873 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6874 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6875 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6876 if (I != ExtnameUndeclaredIdentifiers.end()) {
6877 NewFD->addAttr(I->second);
6878 ExtnameUndeclaredIdentifiers.erase(I);
6879 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006880 }
6881
Chris Lattner9af40c12009-04-25 06:12:16 +00006882 // Copy the parameter declarations from the declarator D to the function
6883 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006884 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006885 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006886 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006887
Zhongxing Xubece5d62009-01-16 01:13:29 +00006888 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6889 // function that takes no arguments, not a function that takes a
6890 // single void argument.
6891 // We let through "const void" here because Sema::GetTypeForDeclarator
6892 // already checks for that case.
6893 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6894 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006895 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00006896 // Empty arg list, don't push any params.
Eli Friedman8f5e9832012-09-20 01:40:23 +00006897 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xubece5d62009-01-16 01:13:29 +00006898 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006899 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00006900 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006901 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6902 Param->setDeclContext(NewFD);
6903 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00006904
6905 if (Param->isInvalidDecl())
6906 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006907 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006908 }
Mike Stump11289f42009-09-09 15:08:12 +00006909
John McCall9dd450b2009-09-21 23:43:11 +00006910 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00006911 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00006912 // following example, we'll need to synthesize (unnamed)
6913 // parameters for use in the declaration.
6914 //
6915 // @code
6916 // typedef void fn(int);
6917 // fn f;
6918 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00006919
Chris Lattner47c0d002009-04-25 06:03:53 +00006920 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00006921 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6922 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00006923 ParmVarDecl *Param =
6924 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00006925 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00006926 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006927 }
Chris Lattner49303b22009-04-25 18:38:18 +00006928 } else {
6929 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6930 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00006931 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00006932
Chris Lattner9af40c12009-04-25 06:12:16 +00006933 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00006934 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00006935
James Molloy6f8780b2012-02-29 10:24:19 +00006936 // Find all anonymous symbols defined during the declaration of this function
6937 // and add to NewFD. This lets us track decls such 'enum Y' in:
6938 //
6939 // void f(enum Y {AA} x) {}
6940 //
6941 // which would otherwise incorrectly end up in the translation unit scope.
6942 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6943 DeclsInPrototypeScope.clear();
6944
Richard Smithdebc59d2013-01-30 05:45:05 +00006945 if (D.getDeclSpec().isNoreturnSpecified())
6946 NewFD->addAttr(
6947 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
Aaron Ballman36a53502014-01-16 13:03:14 +00006948 Context, 0));
Richard Smithdebc59d2013-01-30 05:45:05 +00006949
Richard Smith84208dc2012-03-13 05:56:40 +00006950 // Functions returning a variably modified type violate C99 6.7.5.2p2
6951 // because all functions have linkage.
6952 if (!NewFD->isInvalidDecl() &&
6953 NewFD->getResultType()->isVariablyModifiedType()) {
6954 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6955 NewFD->setInvalidDecl();
6956 }
6957
Rafael Espindolac67f2232012-05-10 02:50:16 +00006958 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00006959 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00006960
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006961 QualType RetType = NewFD->getResultType();
6962 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6963 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6964 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6965 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006966 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramer9940a5d2013-10-16 16:21:04 +00006967 // Attach the attribute to the new decl. Don't apply the attribute if it
6968 // returns an instance of the class (e.g. assignment operators).
6969 if (!MD || MD->getParent() != Ret) {
Aaron Ballman36a53502014-01-16 13:03:14 +00006970 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006971 }
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006972 }
6973
Joey Gouly16cb99d2014-01-06 11:26:18 +00006974 if (getLangOpts().OpenCL) {
6975 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
6976 // type declaration will generate a compilation error.
6977 unsigned AddressSpace = RetType.getAddressSpace();
6978 if (AddressSpace == LangAS::opencl_local ||
6979 AddressSpace == LangAS::opencl_global ||
6980 AddressSpace == LangAS::opencl_constant) {
6981 Diag(NewFD->getLocation(),
6982 diag::err_opencl_return_value_with_address_space);
6983 NewFD->setInvalidDecl();
6984 }
6985 }
6986
David Blaikiebbafb8a2012-03-11 07:00:24 +00006987 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006988 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00006989 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00006990 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6991 CheckMain(NewFD, D.getDeclSpec());
6992
David Majnemerc729b0b2013-09-16 22:44:20 +00006993 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6994 CheckMSVCRTEntryPoint(NewFD);
6995
David Majnemer027f9c42013-07-06 02:13:46 +00006996 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00006997 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6998 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00006999 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007000 // Make graceful recovery from an invalid redeclaration.
7001 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007002 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007003 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7004 "previous declaration set still overloaded");
7005 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007006 // C++11 [replacement.functions]p3:
7007 // The program's definitions shall not be specified as inline.
7008 //
7009 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7010 //
7011 // Suppress the diagnostic if the function is __attribute__((used)), since
7012 // that forces an external definition to be emitted.
7013 if (D.getDeclSpec().isInlineSpecified() &&
7014 NewFD->isReplaceableGlobalAllocationFunction() &&
7015 !NewFD->hasAttr<UsedAttr>())
7016 Diag(D.getDeclSpec().getInlineSpecLoc(),
7017 diag::ext_operator_new_delete_declared_inline)
7018 << NewFD->getDeclName();
7019
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007020 // If the declarator is a template-id, translate the parser's template
7021 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007022 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7023 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7024 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7025 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007026 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007027 TemplateId->NumArgs);
7028 translateTemplateArguments(TemplateArgsPtr,
7029 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007030
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007031 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007032
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007033 if (NewFD->isInvalidDecl()) {
7034 HasExplicitTemplateArgs = false;
7035 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007036 // Function template with explicit template arguments.
7037 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7038 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7039
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007040 HasExplicitTemplateArgs = false;
7041 } else if (!isFunctionTemplateSpecialization &&
7042 !D.getDeclSpec().isFriendSpecified()) {
7043 // We have encountered something that the user meant to be a
7044 // specialization (because it has explicitly-specified template
7045 // arguments) but that was not introduced with a "template<>" (or had
7046 // too few of them).
Larisse Voufo39a1e502013-08-06 01:03:05 +00007047 // FIXME: Differentiate between attempts for explicit instantiations
7048 // (starting with "template") and the rest.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007049 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7050 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7051 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007052 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00007053 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007054 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00007055 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007056 // "friend void foo<>(int);" is an implicit specialization decl.
7057 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007058 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007059 } else if (isFriend && isFunctionTemplateSpecialization) {
7060 // This combination is only possible in a recovery case; the user
7061 // wrote something like:
7062 // template <> friend void foo(int);
7063 // which we're recovering from as if the user had written:
7064 // friend void foo<>(int);
7065 // Go ahead and fake up a template id.
7066 HasExplicitTemplateArgs = true;
7067 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7068 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007069 }
John McCallf7cfb222010-10-13 05:45:15 +00007070
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007071 // If it's a friend (and only if it's a friend), it's possible
7072 // that either the specialized function type or the specialized
7073 // template is dependent, and therefore matching will fail. In
7074 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007075 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007076 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007077 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7078 TemplateSpecializationType::anyDependentTemplateArguments(
7079 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7080 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007081 assert(HasExplicitTemplateArgs &&
7082 "friend function specialization without template args");
7083 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7084 Previous))
7085 NewFD->setInvalidDecl();
7086 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007087 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007088 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007089 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007090 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007091 diag::ext_function_specialization_in_class :
7092 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007093 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007094 } else if (CheckFunctionTemplateSpecialization(NewFD,
7095 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7096 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007097 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007098
7099 // C++ [dcl.stc]p1:
7100 // A storage-class-specifier shall not be specified in an explicit
7101 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007102 FunctionTemplateSpecializationInfo *Info =
7103 NewFD->getTemplateSpecializationInfo();
7104 if (Info && SC != SC_None) {
7105 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007106 Diag(NewFD->getLocation(),
7107 diag::err_explicit_specialization_inconsistent_storage_class)
7108 << SC
7109 << FixItHint::CreateRemoval(
7110 D.getDeclSpec().getStorageClassSpecLoc());
7111
7112 else
7113 Diag(NewFD->getLocation(),
7114 diag::ext_explicit_specialization_storage_class)
7115 << FixItHint::CreateRemoval(
7116 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007117 }
7118
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007119 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7120 if (CheckMemberSpecialization(NewFD, Previous))
7121 NewFD->setInvalidDecl();
7122 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007123
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007124 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007125 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007126 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7127 CheckMain(NewFD, D.getDeclSpec());
7128
David Majnemerc729b0b2013-09-16 22:44:20 +00007129 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7130 CheckMSVCRTEntryPoint(NewFD);
7131
Nico Weber7607fce2013-12-21 00:49:51 +00007132 if (!NewFD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007133 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7134 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007135 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007136
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007137 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007138 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7139 "previous declaration set still overloaded");
7140
7141 NamedDecl *PrincipalDecl = (FunctionTemplate
7142 ? cast<NamedDecl>(FunctionTemplate)
7143 : NewFD);
7144
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007145 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007146 AccessSpecifier Access = AS_public;
7147 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007148 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007149
7150 NewFD->setAccess(Access);
7151 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007152 }
7153
7154 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7155 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7156 PrincipalDecl->setNonMemberOperator();
7157
7158 // If we have a function template, check the template parameter
7159 // list. This will check and merge default template arguments.
7160 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007161 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007162 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007163 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00007164 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007165 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007166 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007167 ? TPC_FriendFunctionTemplateDefinition
7168 : TPC_FriendFunctionTemplate)
7169 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007170 DC && DC->isRecord() &&
7171 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007172 ? TPC_ClassTemplateMember
7173 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007174 }
7175
7176 if (NewFD->isInvalidDecl()) {
7177 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007178 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007179 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007180 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007181 // Fake up an access specifier if it's supposed to be a class member.
7182 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7183 NewFD->setAccess(AS_public);
7184
7185 // Qualified decls generally require a previous declaration.
7186 if (D.getCXXScopeSpec().isSet()) {
7187 // ...with the major exception of templated-scope or
7188 // dependent-scope friend declarations.
7189
7190 // TODO: we currently also suppress this check in dependent
7191 // contexts because (1) the parameter depth will be off when
7192 // matching friend templates and (2) we might actually be
7193 // selecting a friend based on a dependent factor. But there
7194 // are situations where these conditions don't apply and we
7195 // can actually do this check immediately.
7196 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007197 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007198 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7199 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007200 // ignore these
7201 } else {
7202 // The user tried to provide an out-of-line definition for a
7203 // function that is a member of a class or namespace, but there
7204 // was no such member function declared (C++ [class.mfct]p2,
7205 // C++ [namespace.memdef]p2). For example:
7206 //
7207 // class X {
7208 // void f() const;
7209 // };
7210 //
7211 // void X::f() { } // ill-formed
7212 //
7213 // Complain about this problem, and attempt to suggest close
7214 // matches (e.g., those that differ only in cv-qualifiers and
7215 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007216
Richard Smith114394f2013-08-09 04:35:01 +00007217 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7218 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007219 AddToScope = ExtraArgs.AddToScope;
7220 return Result;
7221 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007222 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007223
7224 // Unqualified local friend declarations are required to resolve
7225 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007226 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007227 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7228 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007229 AddToScope = ExtraArgs.AddToScope;
7230 return Result;
7231 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007232 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007233
Richard Smitha2302242013-12-05 07:51:02 +00007234 } else if (!D.isFunctionDefinition() &&
7235 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007236 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007237 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007238 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007239 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007240 // Note that this is not the case for explicit specializations of
7241 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007242 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7243 // extension for compatibility with old SWIG code which likes to
7244 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007245 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7246 << D.getCXXScopeSpec().getRange();
7247 }
7248 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007249
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007250 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007251 checkAttributesAfterMerging(*this, *NewFD);
7252
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007253 AddKnownFunctionAttributes(NewFD);
7254
Douglas Gregor72609052010-08-06 13:50:58 +00007255 if (NewFD->hasAttr<OverloadableAttr>() &&
7256 !NewFD->getType()->getAs<FunctionProtoType>()) {
7257 Diag(NewFD->getLocation(),
7258 diag::err_attribute_overloadable_no_prototype)
7259 << NewFD;
7260
7261 // Turn this into a variadic function with no parameters.
7262 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007263 FunctionProtoType::ExtProtoInfo EPI(
7264 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007265 EPI.Variadic = true;
7266 EPI.ExtInfo = FT->getExtInfo();
7267
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007268 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007269 NewFD->setType(R);
7270 }
7271
Eli Friedman570024a2010-08-05 06:57:20 +00007272 // If there's a #pragma GCC visibility in scope, and this isn't a class
7273 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007274 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007275 AddPushedVisibilityAttribute(NewFD);
7276
John McCall32f5fe12011-09-30 05:12:12 +00007277 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7278 // marking the function.
7279 AddCFAuditedAttribute(NewFD);
7280
Richard Smithac974a32013-06-30 09:48:50 +00007281 // If this is the first declaration of an extern C variable, update
7282 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007283 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007284 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007285 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007286
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007287 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007288 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007289
David Blaikiebbafb8a2012-03-11 07:00:24 +00007290 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007291 if (FunctionTemplate) {
7292 if (NewFD->isInvalidDecl())
7293 FunctionTemplate->setInvalidDecl();
7294 return FunctionTemplate;
7295 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007296 }
Mike Stump11289f42009-09-09 15:08:12 +00007297
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007298 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007299 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7300 if ((getLangOpts().OpenCLVersion >= 120)
7301 && (SC == SC_Static)) {
7302 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7303 D.setInvalidType();
7304 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007305
7306 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7307 if (!NewFD->getResultType()->isVoidType()) {
7308 Diag(D.getIdentifierLoc(),
7309 diag::err_expected_kernel_void_return_type);
7310 D.setInvalidType();
7311 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007312
7313 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007314 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7315 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly39989da2013-01-29 10:54:06 +00007316 ParmVarDecl *Param = *PI;
Matt Arsenaultefb38192013-07-23 01:23:36 +00007317 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007318 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007319 }
7320
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007321 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007322
David Blaikiebbafb8a2012-03-11 07:00:24 +00007323 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007324 if (IdentifierInfo *II = NewFD->getIdentifier())
7325 if (!NewFD->isInvalidDecl() &&
7326 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7327 if (II->isStr("cudaConfigureCall")) {
7328 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7329 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7330
7331 Context.setcudaConfigureCallDecl(NewFD);
7332 }
7333 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007334
7335 // Here we have an function template explicit specialization at class scope.
7336 // The actually specialization will be postponed to template instatiation
7337 // time via the ClassScopeFunctionSpecializationDecl node.
7338 if (isDependentClassScopeExplicitSpecialization) {
7339 ClassScopeFunctionSpecializationDecl *NewSpec =
7340 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007341 Context, CurContext, SourceLocation(),
7342 cast<CXXMethodDecl>(NewFD),
7343 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007344 CurContext->addDecl(NewSpec);
7345 AddToScope = false;
7346 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007347
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007348 return NewFD;
7349}
7350
7351/// \brief Perform semantic checking of a new function declaration.
7352///
7353/// Performs semantic analysis of the new function declaration
7354/// NewFD. This routine performs all semantic checking that does not
7355/// require the actual declarator involved in the declaration, and is
7356/// used both for the declaration of functions as they are parsed
7357/// (called via ActOnDeclarator) and for the declaration of functions
7358/// that have been instantiated via C++ template instantiation (called
7359/// via InstantiateDecl).
7360///
James Dennettffad8b72012-06-22 08:10:18 +00007361/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007362/// an explicit specialization of the previous declaration.
7363///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007364/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007365///
James Dennettffad8b72012-06-22 08:10:18 +00007366/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007367bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007368 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007369 bool IsExplicitSpecialization) {
David Blaikied937bf12011-09-08 06:33:04 +00007370 assert(!NewFD->getResultType()->isVariablyModifiedType()
7371 && "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007372
Richard Smith1c34fb72013-08-13 18:18:50 +00007373 // Determine whether the type of this function should be merged with
7374 // a previous visible declaration. This never happens for functions in C++,
7375 // and always happens in C if the previous declaration was visible.
7376 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7377 !Previous.isShadowed();
7378
Douglas Gregor3552dab2013-01-09 00:47:56 +00007379 // Filter out any non-conflicting previous declarations.
7380 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7381
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007382 bool Redeclaration = false;
Richard Smith574f4f62013-01-14 05:37:29 +00007383 NamedDecl *OldDecl = 0;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007384
Douglas Gregore62c0a42009-02-24 01:23:02 +00007385 // Merge or overload the declaration with an existing declaration of
7386 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007387 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007388 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007389 // a declaration that requires merging. If it's an overload,
7390 // there's no more work to do here; we'll just add the new
7391 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007392 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007393 NamedDecl *Candidate = Previous.getFoundDecl();
7394 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7395 Redeclaration = true;
7396 OldDecl = Candidate;
7397 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007398 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007399 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7400 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007401 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007402 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007403 break;
7404
7405 case Ovl_NonFunction:
7406 Redeclaration = true;
7407 break;
7408
7409 case Ovl_Overload:
7410 Redeclaration = false;
7411 break;
John McCall1f82f242009-11-18 22:49:29 +00007412 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007413
David Blaikiebbafb8a2012-03-11 07:00:24 +00007414 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007415 // If a function name is overloadable in C, then every function
7416 // with that name must be marked "overloadable".
7417 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7418 << Redeclaration << NewFD;
7419 NamedDecl *OverloadedDecl = 0;
7420 if (Redeclaration)
7421 OverloadedDecl = OldDecl;
7422 else if (!Previous.empty())
7423 OverloadedDecl = Previous.getRepresentativeDecl();
7424 if (OverloadedDecl)
7425 Diag(OverloadedDecl->getLocation(),
7426 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007427 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007428 }
John McCall1f82f242009-11-18 22:49:29 +00007429 }
Richard Smith574f4f62013-01-14 05:37:29 +00007430 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007431
Richard Smithac974a32013-06-30 09:48:50 +00007432 // Check for a previous extern "C" declaration with this name.
7433 if (!Redeclaration &&
7434 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7435 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7436 if (!Previous.empty()) {
7437 // This is an extern "C" declaration with the same name as a previous
7438 // declaration, and thus redeclares that entity...
7439 Redeclaration = true;
7440 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007441 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007442
7443 // ... except in the presence of __attribute__((overloadable)).
7444 if (OldDecl->hasAttr<OverloadableAttr>()) {
7445 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7446 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7447 << Redeclaration << NewFD;
7448 Diag(Previous.getFoundDecl()->getLocation(),
7449 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007450 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007451 }
7452 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7453 Redeclaration = false;
7454 OldDecl = 0;
7455 }
7456 }
7457 }
7458 }
7459
Richard Smith574f4f62013-01-14 05:37:29 +00007460 // C++11 [dcl.constexpr]p8:
7461 // A constexpr specifier for a non-static member function that is not
7462 // a constructor declares that member function to be const.
7463 //
7464 // This needs to be delayed until we know whether this is an out-of-line
7465 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007466 //
7467 // This rule is not present in C++1y, so we produce a backwards
7468 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007469 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007470 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7471 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007472 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7473 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7474 if (FunctionTemplateDecl *OldTD =
7475 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7476 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7477 if (!OldMD || !OldMD->isStatic()) {
7478 const FunctionProtoType *FPT =
7479 MD->getType()->castAs<FunctionProtoType>();
7480 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7481 EPI.TypeQuals |= Qualifiers::Const;
7482 MD->setType(Context.getFunctionType(FPT->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00007483 FPT->getArgTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007484
7485 // Warn that we did this, if we're not performing template instantiation.
7486 // In that case, we'll have warned already when the template was defined.
7487 if (ActiveTemplateInstantiations.empty()) {
7488 SourceLocation AddConstLoc;
7489 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7490 .IgnoreParens().getAs<FunctionTypeLoc>())
7491 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7492
7493 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7494 << FixItHint::CreateInsertion(AddConstLoc, " const");
7495 }
Richard Smith574f4f62013-01-14 05:37:29 +00007496 }
7497 }
7498
7499 if (Redeclaration) {
7500 // NewFD and OldDecl represent declarations that need to be
7501 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007502 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007503 NewFD->setInvalidDecl();
7504 return Redeclaration;
7505 }
7506
7507 Previous.clear();
7508 Previous.addDecl(OldDecl);
7509
7510 if (FunctionTemplateDecl *OldTemplateDecl
7511 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7512 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7513 FunctionTemplateDecl *NewTemplateDecl
7514 = NewFD->getDescribedFunctionTemplate();
7515 assert(NewTemplateDecl && "Template/non-template mismatch");
7516 if (CXXMethodDecl *Method
7517 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7518 Method->setAccess(OldTemplateDecl->getAccess());
7519 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007520 }
Richard Smith574f4f62013-01-14 05:37:29 +00007521
7522 // If this is an explicit specialization of a member that is a function
7523 // template, mark it as a member specialization.
7524 if (IsExplicitSpecialization &&
7525 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7526 NewTemplateDecl->setMemberSpecialization();
7527 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007528 }
Richard Smith574f4f62013-01-14 05:37:29 +00007529
7530 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007531 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007532 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007533
7534 if (isa<CXXMethodDecl>(NewFD)) {
7535 // A valid redeclaration of a C++ method must be out-of-line,
7536 // but (unfortunately) it's not necessarily a definition
7537 // because of templates, which means that the previous
7538 // declaration is not necessarily from the class definition.
7539
7540 // For just setting the access, that doesn't matter.
7541 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7542 NewFD->setAccess(oldMethod->getAccess());
7543
7544 // Update the key-function state if necessary for this ABI.
7545 if (NewFD->isInlined() &&
7546 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7547 // setNonKeyFunction needs to work with the original
7548 // declaration from the class definition, and isVirtual() is
7549 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007550 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007551 if (oldMethod->isVirtual()) {
7552 Context.setNonKeyFunction(oldMethod);
7553 }
7554 }
7555 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007556 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007557 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007558
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007559 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007560 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007561 // C++-specific checks.
7562 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7563 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007564 } else if (CXXDestructorDecl *Destructor =
7565 dyn_cast<CXXDestructorDecl>(NewFD)) {
7566 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007567 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007568
Douglas Gregor7454c562010-07-02 20:37:36 +00007569 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007570 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007571 if (!ClassType->isDependentType()) {
7572 DeclarationName Name
7573 = Context.DeclarationNames.getCXXDestructorName(
7574 Context.getCanonicalType(ClassType));
7575 if (NewFD->getDeclName() != Name) {
7576 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007577 NewFD->setInvalidDecl();
7578 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007579 }
7580 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007581 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007582 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007583 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007584 }
7585
7586 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007587 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7588 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007589 !Method->getDescribedFunctionTemplate() &&
7590 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007591 if (AddOverriddenMethods(Method->getParent(), Method)) {
7592 // If the function was marked as "static", we have a problem.
7593 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007594 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007595 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007596 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007597 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007598
7599 if (Method->isStatic())
7600 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007601 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007602
7603 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7604 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007605 CheckOverloadedOperatorDeclaration(NewFD)) {
7606 NewFD->setInvalidDecl();
7607 return Redeclaration;
7608 }
Alexis Huntc88db062010-01-13 09:01:02 +00007609
7610 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7611 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007612 CheckLiteralOperatorDeclaration(NewFD)) {
7613 NewFD->setInvalidDecl();
7614 return Redeclaration;
7615 }
Alexis Huntc88db062010-01-13 09:01:02 +00007616
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007617 // In C++, check default arguments now that we have merged decls. Unless
7618 // the lexical context is the class, because in this case this is done
7619 // during delayed parsing anyway.
7620 if (!CurContext->isRecord())
7621 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007622
Douglas Gregor9246b682010-12-21 19:47:46 +00007623 // If this function declares a builtin function, check the type of this
7624 // declaration against the expected type for the builtin.
7625 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7626 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007627 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007628 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7629 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7630 // The type of this function differs from the type of the builtin,
7631 // so forget about the builtin entirely.
7632 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7633 }
7634 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007635
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007636 // If this function is declared as being extern "C", then check to see if
7637 // the function returns a UDT (class, struct, or union type) that is not C
7638 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007639 // But, issue any diagnostic on the first declaration only.
7640 if (NewFD->isExternC() && Previous.empty()) {
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007641 QualType R = NewFD->getResultType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007642 if (R->isIncompleteType() && !R->isVoidType())
7643 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7644 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007645 else if (!R.isPODType(Context) && !R->isVoidType() &&
7646 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007647 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007648 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007649 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007650 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007651}
7652
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007653static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7654 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7655 if (!TSI)
7656 return SourceRange();
7657
7658 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007659 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007660 if (!FunctionTL)
7661 return SourceRange();
7662
David Blaikie6adc78e2013-02-18 22:06:02 +00007663 TypeLoc ResultTL = FunctionTL.getResultLoc();
7664 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007665 return ResultTL.getSourceRange();
7666
7667 return SourceRange();
7668}
7669
David Blaikied937bf12011-09-08 06:33:04 +00007670void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smith3f333f22012-02-04 06:10:17 +00007671 // C++11 [basic.start.main]p3: A program that declares main to be inline,
7672 // static or constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007673 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7674 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007675 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007676 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007677 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007678 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007679 ? diag::err_static_main : diag::warn_static_main)
7680 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7681 if (FD->isInlineSpecified())
7682 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7683 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007684 if (DS.isNoreturnSpecified()) {
7685 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7686 SourceRange NoreturnRange(NoreturnLoc,
7687 PP.getLocForEndOfToken(NoreturnLoc));
7688 Diag(NoreturnLoc, diag::ext_noreturn_main);
7689 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7690 << FixItHint::CreateRemoval(NoreturnRange);
7691 }
Richard Smith3f333f22012-02-04 06:10:17 +00007692 if (FD->isConstexpr()) {
7693 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7694 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7695 FD->setConstexpr(false);
7696 }
John McCall02dee0a2009-07-25 04:36:53 +00007697
Joey Goulya7310a82013-11-05 12:30:39 +00007698 if (getLangOpts().OpenCL) {
7699 Diag(FD->getLocation(), diag::err_opencl_no_main)
7700 << FD->hasAttr<OpenCLKernelAttr>();
7701 FD->setInvalidDecl();
7702 return;
7703 }
7704
John McCall02dee0a2009-07-25 04:36:53 +00007705 QualType T = FD->getType();
7706 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007707 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007708
John McCall5ed3caf2012-02-14 19:50:52 +00007709 // All the standards say that main() should should return 'int'.
7710 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7711 // In C and C++, main magically returns 0 if you fall off the end;
7712 // set the flag which tells us that.
7713 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7714 FD->setHasImplicitReturnZero(true);
7715
7716 // In C with GNU extensions we allow main() to have non-integer return
7717 // type, but we should warn about the extension, and we disable the
7718 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007719 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007720 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7721
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007722 SourceRange ResultRange = getResultSourceRange(FD);
7723 if (ResultRange.isValid())
7724 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7725 << FixItHint::CreateReplacement(ResultRange, "int");
7726
John McCall5ed3caf2012-02-14 19:50:52 +00007727 // Otherwise, this is just a flat-out error.
7728 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007729 SourceRange ResultRange = getResultSourceRange(FD);
7730 if (ResultRange.isValid())
7731 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7732 << FixItHint::CreateReplacement(ResultRange, "int");
7733 else
7734 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7735
John McCall02dee0a2009-07-25 04:36:53 +00007736 FD->setInvalidDecl(true);
7737 }
7738
7739 // Treat protoless main() as nullary.
7740 if (isa<FunctionNoProtoType>(FT)) return;
7741
7742 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7743 unsigned nparams = FTP->getNumArgs();
7744 assert(FD->getNumParams() == nparams);
7745
John McCall0e21fcc2009-12-24 09:58:38 +00007746 bool HasExtraParameters = (nparams > 3);
7747
7748 // Darwin passes an undocumented fourth argument of type char**. If
7749 // other platforms start sprouting these, the logic below will start
7750 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007751 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007752 HasExtraParameters = false;
7753
7754 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007755 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7756 FD->setInvalidDecl(true);
7757 nparams = 3;
7758 }
7759
7760 // FIXME: a lot of the following diagnostics would be improved
7761 // if we had some location information about types.
7762
7763 QualType CharPP =
7764 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007765 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007766
7767 for (unsigned i = 0; i < nparams; ++i) {
7768 QualType AT = FTP->getArgType(i);
7769
7770 bool mismatch = true;
7771
7772 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7773 mismatch = false;
7774 else if (Expected[i] == CharPP) {
7775 // As an extension, the following forms are okay:
7776 // char const **
7777 // char const * const *
7778 // char * const *
7779
John McCall8ccfcb52009-09-24 19:53:00 +00007780 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007781 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007782 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7783 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007784 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7785 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007786 qs.removeConst();
7787 mismatch = !qs.empty();
7788 }
7789 }
7790
7791 if (mismatch) {
7792 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7793 // TODO: suggest replacing given type with expected type
7794 FD->setInvalidDecl(true);
7795 }
7796 }
7797
7798 if (nparams == 1 && !FD->isInvalidDecl()) {
7799 Diag(FD->getLocation(), diag::warn_main_one_arg);
7800 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007801
7802 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007803 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007804 FD->setInvalidDecl();
7805 }
7806}
7807
7808void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7809 QualType T = FD->getType();
7810 assert(T->isFunctionType() && "function decl is not of function type");
7811 const FunctionType *FT = T->castAs<FunctionType>();
7812
7813 // Set an implicit return of 'zero' if the function can return some integral,
7814 // enumeration, pointer or nullptr type.
7815 if (FT->getResultType()->isIntegralOrEnumerationType() ||
7816 FT->getResultType()->isAnyPointerType() ||
7817 FT->getResultType()->isNullPtrType())
7818 // DllMain is exempt because a return value of zero means it failed.
7819 if (FD->getName() != "DllMain")
7820 FD->setHasImplicitReturnZero(true);
7821
7822 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007823 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007824 FD->setInvalidDecl();
7825 }
John McCalld9baf6a2009-07-24 03:03:21 +00007826}
7827
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007828bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007829 // FIXME: Need strict checking. In C89, we need to check for
7830 // any assignment, increment, decrement, function-calls, or
7831 // commas outside of a sizeof. In C99, it's the same list,
7832 // except that the aforementioned are allowed in unevaluated
7833 // expressions. Everything else falls under the
7834 // "may accept other forms of constant expressions" exception.
7835 // (We never end up here for C++, so the constant expression
7836 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007837 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007838 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007839 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7840 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007841 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007842}
7843
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007844namespace {
7845 // Visits an initialization expression to see if OrigDecl is evaluated in
7846 // its own initialization and throws a warning if it does.
7847 class SelfReferenceChecker
7848 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7849 Sema &S;
7850 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007851 bool isRecordType;
7852 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007853 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007854
7855 public:
7856 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7857
7858 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007859 S(S), OrigDecl(OrigDecl) {
7860 isPODType = false;
7861 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007862 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007863 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7864 isPODType = VD->getType().isPODType(S.Context);
7865 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007866 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007867 }
7868 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007869
Richard Trieu64c51ab2012-05-09 00:21:34 +00007870 // For most expressions, the cast is directly above the DeclRefExpr.
7871 // For conditional operators, the cast can be outside the conditional
7872 // operator if both expressions are DeclRefExpr's.
7873 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007874 if (isReferenceType)
7875 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007876 E = E->IgnoreParenImpCasts();
7877 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7878 HandleDeclRefExpr(DRE);
7879 return;
7880 }
7881
7882 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7883 HandleValue(CO->getTrueExpr());
7884 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007885 return;
7886 }
7887
7888 if (isa<MemberExpr>(E)) {
7889 Expr *Base = E->IgnoreParenImpCasts();
7890 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7891 // Check for static member variables and don't warn on them.
7892 if (!isa<FieldDecl>(ME->getMemberDecl()))
7893 return;
7894 Base = ME->getBase()->IgnoreParenImpCasts();
7895 }
7896 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7897 HandleDeclRefExpr(DRE);
7898 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007899 }
7900 }
7901
Richard Trieu32673472012-10-01 17:39:51 +00007902 // Reference types are handled here since all uses of references are
7903 // bad, not just r-value uses.
7904 void VisitDeclRefExpr(DeclRefExpr *E) {
7905 if (isReferenceType)
7906 HandleDeclRefExpr(E);
7907 }
7908
Richard Trieu64c51ab2012-05-09 00:21:34 +00007909 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00007910 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00007911 (isRecordType && E->getCastKind() == CK_NoOp))
7912 HandleValue(E->getSubExpr());
7913
7914 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007915 }
7916
Richard Trieua04ad1a2011-09-01 21:44:13 +00007917 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00007918 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00007919 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007920
Richard Trieu742c6ed2012-10-03 00:41:36 +00007921 // Warn when a non-static method call is followed by non-static member
7922 // field accesses, which is followed by a DeclRefExpr.
7923 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7924 bool Warn = (MD && !MD->isStatic());
7925 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7926 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7927 if (!isa<FieldDecl>(ME->getMemberDecl()))
7928 Warn = false;
7929 Base = ME->getBase()->IgnoreParenImpCasts();
7930 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007931
Richard Trieu742c6ed2012-10-03 00:41:36 +00007932 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7933 if (Warn)
7934 HandleDeclRefExpr(DRE);
7935 return;
7936 }
7937
7938 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7939 // Visit that expression.
7940 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007941 }
7942
Richard Trieu8fbd91d2013-03-26 03:41:40 +00007943 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7944 if (E->getNumArgs() > 0)
7945 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7946 HandleDeclRefExpr(DRE);
7947
7948 Inherited::VisitCXXOperatorCallExpr(E);
7949 }
7950
Richard Trieua04ad1a2011-09-01 21:44:13 +00007951 void VisitUnaryOperator(UnaryOperator *E) {
7952 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00007953 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7954 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7955 if (!isPODType)
7956 HandleValue(E->getSubExpr());
7957 return;
7958 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007959 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00007960 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00007961
7962 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7963
Richard Trieua04ad1a2011-09-01 21:44:13 +00007964 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00007965 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007966 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00007967 unsigned diag;
7968 if (isReferenceType) {
7969 diag = diag::warn_uninit_self_reference_in_reference_init;
7970 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7971 diag = diag::warn_static_self_reference_in_init;
7972 } else {
7973 diag = diag::warn_uninit_self_reference_in_init;
7974 }
7975
Richard Trieua04ad1a2011-09-01 21:44:13 +00007976 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00007977 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00007978 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007979 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00007980 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007981 }
7982 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007983
Richard Trieu32673472012-10-01 17:39:51 +00007984 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7985 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7986 bool DirectInit) {
7987 // Parameters arguments are occassionially constructed with itself,
7988 // for instance, in recursive functions. Skip them.
7989 if (isa<ParmVarDecl>(OrigDecl))
7990 return;
7991
7992 E = E->IgnoreParens();
7993
7994 // Skip checking T a = a where T is not a record or reference type.
7995 // Doing so is a way to silence uninitialized warnings.
7996 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7997 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7998 if (ICE->getCastKind() == CK_LValueToRValue)
7999 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8000 if (DRE->getDecl() == OrigDecl)
8001 return;
8002
8003 SelfReferenceChecker(S, OrigDecl).Visit(E);
8004 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008005}
8006
Douglas Gregor5fb53972009-01-14 15:45:31 +00008007/// AddInitializerToDecl - Adds the initializer Init to the
8008/// declaration dcl. If DirectInit is true, this is C++ direct
8009/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008010void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8011 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008012 // If there is no declaration, there was an error parsing it. Just ignore
8013 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008014 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008015 return;
Mike Stump11289f42009-09-09 15:08:12 +00008016
Douglas Gregor0c880302009-03-11 23:00:04 +00008017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8018 // With declarators parsed the way they are, the parser cannot
8019 // distinguish between a normal initializer and a pure-specifier.
8020 // Thus this grotesque test.
8021 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008022 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008023 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8024 CheckPureMethod(Method, Init->getSourceRange());
8025 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008026 Diag(Method->getLocation(), diag::err_member_function_initialization)
8027 << Method->getDeclName() << Init->getSourceRange();
8028 Method->setInvalidDecl();
8029 }
8030 return;
8031 }
8032
Steve Naroff437b4d82007-09-12 20:13:48 +00008033 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8034 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008035 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8036 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008037 RealDecl->setInvalidDecl();
8038 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008039 }
Sebastian Redla9351792012-02-11 23:51:47 +00008040 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8041
Richard Smith0cc85782011-12-15 19:20:59 +00008042 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008043 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008044 Expr *DeduceInit = Init;
8045 // Initializer could be a C++ direct-initializer. Deduction only works if it
8046 // contains exactly one expression.
8047 if (CXXDirectInit) {
8048 if (CXXDirectInit->getNumExprs() == 0) {
8049 // It isn't possible to write this directly, but it is possible to
8050 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008051 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008052 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8053 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008054 << VDecl->getDeclName() << VDecl->getType()
8055 << VDecl->getSourceRange();
8056 RealDecl->setInvalidDecl();
8057 return;
8058 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008059 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008060 VDecl->isInitCapture()
8061 ? diag::err_init_capture_multiple_expressions
8062 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008063 << VDecl->getDeclName() << VDecl->getType()
8064 << VDecl->getSourceRange();
8065 RealDecl->setInvalidDecl();
8066 return;
8067 } else {
8068 DeduceInit = CXXDirectInit->getExpr(0);
8069 }
8070 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008071
8072 // Expressions default to 'id' when we're in a debugger.
8073 bool DefaultedToAuto = false;
8074 if (getLangOpts().DebuggerCastResultToId &&
8075 Init->getType() == Context.UnknownAnyTy) {
8076 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8077 if (Result.isInvalid()) {
8078 VDecl->setInvalidDecl();
8079 return;
8080 }
8081 Init = Result.take();
8082 DefaultedToAuto = true;
8083 }
Richard Smith061f1e22013-04-30 21:23:01 +00008084
8085 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008086 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008087 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008088 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008089 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008090 RealDecl->setInvalidDecl();
8091 return;
8092 }
Richard Smith061f1e22013-04-30 21:23:01 +00008093 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008094 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008095
John McCall31168b02011-06-15 23:02:42 +00008096 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008097 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008098 VDecl->setInvalidDecl();
8099
Jordan Rosed8d56692012-06-08 22:46:07 +00008100 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8101 // 'id' instead of a specific object type prevents most of our usual checks.
8102 // We only want to warn outside of template instantiations, though:
8103 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008104 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008105 DeducedType->isObjCIdType()) {
8106 SourceLocation Loc =
8107 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008108 Diag(Loc, diag::warn_auto_var_is_id)
8109 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8110 }
8111
Richard Smith30482bc2011-02-20 03:19:35 +00008112 // If this is a redeclaration, check that the type we just deduced matches
8113 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008114 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8115 // We never need to merge the type, because we cannot form an incomplete
8116 // array of auto, nor deduce such a type.
8117 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8118 }
Richard Smith27d807c2013-04-30 13:56:41 +00008119
8120 // Check the deduced type is valid for a variable declaration.
8121 CheckVariableDeclarationType(VDecl);
8122 if (VDecl->isInvalidDecl())
8123 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008124 }
Richard Smith0cc85782011-12-15 19:20:59 +00008125
8126 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8127 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8128 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8129 VDecl->setInvalidDecl();
8130 return;
8131 }
8132
Sebastian Redla9351792012-02-11 23:51:47 +00008133 if (!VDecl->getType()->isDependentType()) {
8134 // A definition must end up with a complete type, which means it must be
8135 // complete with the restriction that an array type might be completed by
8136 // the initializer; note that later code assumes this restriction.
8137 QualType BaseDeclType = VDecl->getType();
8138 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8139 BaseDeclType = Array->getElementType();
8140 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8141 diag::err_typecheck_decl_incomplete_type)) {
8142 RealDecl->setInvalidDecl();
8143 return;
8144 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008145
Sebastian Redla9351792012-02-11 23:51:47 +00008146 // The variable can not have an abstract class type.
8147 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8148 diag::err_abstract_type_in_decl,
8149 AbstractVariableType))
8150 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008151 }
8152
Sebastian Redl5ca79842010-02-01 20:16:42 +00008153 const VarDecl *Def;
8154 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008155 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008156 << VDecl->getDeclName();
8157 Diag(Def->getLocation(), diag::note_previous_definition);
8158 VDecl->setInvalidDecl();
8159 return;
8160 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008161
Douglas Gregorf0f83692010-08-24 05:27:49 +00008162 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008163 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008164 // C++ [class.static.data]p4
8165 // If a static data member is of const integral or const
8166 // enumeration type, its declaration in the class definition can
8167 // specify a constant-initializer which shall be an integral
8168 // constant expression (5.19). In that case, the member can appear
8169 // in integral constant expressions. The member shall still be
8170 // defined in a namespace scope if it is used in the program and the
8171 // namespace scope definition shall not contain an initializer.
8172 //
8173 // We already performed a redefinition check above, but for static
8174 // data members we also need to check whether there was an in-class
8175 // declaration with an initializer.
8176 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008177 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8178 << VDecl->getDeclName();
8179 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008180 return;
8181 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008182
Douglas Gregor71f39c92010-12-16 01:31:22 +00008183 if (VDecl->hasLocalStorage())
8184 getCurFunction()->setHasBranchProtectedScope();
8185
8186 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8187 VDecl->setInvalidDecl();
8188 return;
8189 }
8190 }
John McCalld4e1b762010-08-01 01:24:59 +00008191
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008192 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8193 // a kernel function cannot be initialized."
8194 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8195 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8196 VDecl->setInvalidDecl();
8197 return;
8198 }
8199
Steve Naroff61091402007-09-12 14:07:44 +00008200 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008201 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008202 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008203
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008204 // Expressions default to 'id' when we're in a debugger
8205 // and we are assigning it to a variable of Objective-C pointer type.
8206 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8207 Init->getType() == Context.UnknownAnyTy) {
8208 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8209 if (Result.isInvalid()) {
8210 VDecl->setInvalidDecl();
8211 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008212 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008213 Init = Result.take();
8214 }
Richard Smith0cc85782011-12-15 19:20:59 +00008215
8216 // Perform the initialization.
8217 if (!VDecl->isInvalidDecl()) {
8218 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8219 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008220 = DirectInit ?
8221 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8222 Init->getLocStart(),
8223 Init->getLocEnd())
8224 : InitializationKind::CreateDirectList(
8225 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008226 : InitializationKind::CreateCopy(VDecl->getLocation(),
8227 Init->getLocStart());
8228
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008229 MultiExprArg Args = Init;
8230 if (CXXDirectInit)
8231 Args = MultiExprArg(CXXDirectInit->getExprs(),
8232 CXXDirectInit->getNumExprs());
8233
8234 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8235 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008236 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008237 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008238 return;
Steve Naroff61091402007-09-12 14:07:44 +00008239 }
Richard Smith0cc85782011-12-15 19:20:59 +00008240
8241 Init = Result.takeAs<Expr>();
8242 }
8243
Richard Trieu32673472012-10-01 17:39:51 +00008244 // Check for self-references within variable initializers.
8245 // Variables declared within a function/method body (except for references)
8246 // are handled by a dataflow analysis.
8247 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8248 VDecl->getType()->isReferenceType()) {
8249 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8250 }
8251
Richard Smith0cc85782011-12-15 19:20:59 +00008252 // If the type changed, it means we had an incomplete type that was
8253 // completed by the initializer. For example:
8254 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008255 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008256 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008257 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008258
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008259 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008260 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8261
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008262 if (VDecl->hasAttr<BlocksAttr>())
8263 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008264
8265 // It is safe to assign a weak reference into a strong variable.
8266 // Although this code can still have problems:
8267 // id x = self.weakProp;
8268 // id y = self.weakProp;
8269 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8270 // paths through the function. This should be revisited if
8271 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008272 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008273 DiagnosticsEngine::Level Level =
8274 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8275 Init->getLocStart());
8276 if (Level != DiagnosticsEngine::Ignored)
8277 getCurFunction()->markSafeWeakUse(Init);
8278 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008279 }
8280
Richard Smith945f8d32013-01-14 22:39:08 +00008281 // The initialization is usually a full-expression.
8282 //
8283 // FIXME: If this is a braced initialization of an aggregate, it is not
8284 // an expression, and each individual field initializer is a separate
8285 // full-expression. For instance, in:
8286 //
8287 // struct Temp { ~Temp(); };
8288 // struct S { S(Temp); };
8289 // struct T { S a, b; } t = { Temp(), Temp() }
8290 //
8291 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008292 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8293 false,
8294 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008295 if (Result.isInvalid()) {
8296 VDecl->setInvalidDecl();
8297 return;
8298 }
8299 Init = Result.take();
8300
Richard Smith0cc85782011-12-15 19:20:59 +00008301 // Attach the initializer to the decl.
8302 VDecl->setInit(Init);
8303
8304 if (VDecl->isLocalVarDecl()) {
8305 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8306 // static storage duration shall be constant expressions or string literals.
8307 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008308 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8309 if (VDecl->getStorageClass() == SC_Static)
8310 CheckForConstantInitializer(Init, DclT);
8311 // C89 is stricter than C99 for non-static aggregate types.
8312 // C89 6.5.7p3: All the expressions [...] in an initializer list
8313 // for an object that has aggregate or union type shall be
8314 // constant expressions.
8315 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008316 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008317 !Init->isConstantInitializer(Context, false))
8318 Diag(Init->getExprLoc(),
8319 diag::ext_aggregate_init_not_constant)
8320 << Init->getSourceRange();
8321 }
Mike Stump11289f42009-09-09 15:08:12 +00008322 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008323 VDecl->getLexicalDeclContext()->isRecord()) {
8324 // This is an in-class initialization for a static data member, e.g.,
8325 //
8326 // struct S {
8327 // static const int value = 17;
8328 // };
8329
Douglas Gregor0c880302009-03-11 23:00:04 +00008330 // C++ [class.mem]p4:
8331 // A member-declarator can contain a constant-initializer only
8332 // if it declares a static member (9.4) of const integral or
8333 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008334 //
Richard Smith0cc85782011-12-15 19:20:59 +00008335 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008336 // If a non-volatile const static data member is of integral or
8337 // enumeration type, its declaration in the class definition can
8338 // specify a brace-or-equal-initializer in which every initalizer-clause
8339 // that is an assignment-expression is a constant expression. A static
8340 // data member of literal type can be declared in the class definition
8341 // with the constexpr specifier; if so, its declaration shall specify a
8342 // brace-or-equal-initializer in which every initializer-clause that is
8343 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008344
8345 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008346 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008347
Richard Smith2316cd82011-09-29 19:11:37 +00008348 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008349 // type. We separately check that every constexpr variable is of literal
8350 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008351 } else if (VDecl->isConstexpr()) {
8352
John McCalldb768922010-09-10 23:21:22 +00008353 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008354 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008355 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8356 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008357 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008358
8359 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008360 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008361 // Check whether the expression is a constant expression.
8362 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008363 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008364 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008365 // in-class initializer cannot be volatile.
8366 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8367 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008368 ; // Nothing to check.
8369 else if (Init->isIntegerConstantExpr(Context, &Loc))
8370 ; // Ok, it's an ICE!
8371 else if (Init->isEvaluatable(Context)) {
8372 // If we can constant fold the initializer through heroics, accept it,
8373 // but report this as a use of an extension for -pedantic.
8374 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8375 << Init->getSourceRange();
8376 } else {
8377 // Otherwise, this is some crazy unknown case. Report the issue at the
8378 // location provided by the isIntegerConstantExpr failed check.
8379 Diag(Loc, diag::err_in_class_initializer_non_constant)
8380 << Init->getSourceRange();
8381 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008382 }
8383
Richard Smith0cc85782011-12-15 19:20:59 +00008384 // We allow foldable floating-point constants as an extension.
8385 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008386 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8387 // it anyway and provide a fixit to add the 'constexpr'.
8388 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008389 Diag(VDecl->getLocation(),
8390 diag::ext_in_class_initializer_float_type_cxx11)
8391 << DclT << Init->getSourceRange();
8392 Diag(VDecl->getLocStart(),
8393 diag::note_in_class_initializer_float_type_cxx11)
8394 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008395 } else {
8396 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8397 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008398
Richard Smithcf656382013-01-25 04:22:16 +00008399 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8400 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8401 << Init->getSourceRange();
8402 VDecl->setInvalidDecl();
8403 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008404 }
Richard Smith256336d2011-09-29 23:18:34 +00008405
Richard Smith0cc85782011-12-15 19:20:59 +00008406 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008407 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008408 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008409 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008410 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8411 VDecl->setConstexpr(true);
8412
Richard Smith2316cd82011-09-29 19:11:37 +00008413 } else {
8414 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008415 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008416 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008417 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008418 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008419 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008420 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008421 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008422 VDecl->isExternC())) &&
8423 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008424 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008425
Richard Smith0cc85782011-12-15 19:20:59 +00008426 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008427 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008428 CheckForConstantInitializer(Init, DclT);
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008429 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8430 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8431 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smith774672e2013-04-15 08:07:34 +00008432 !Init->isConstantInitializer(
8433 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008434 // GNU C++98 edits for __thread, [basic.start.init]p4:
8435 // An object of thread storage duration shall not require dynamic
8436 // initialization.
8437 // FIXME: Need strict checking here.
8438 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8439 if (getLangOpts().CPlusPlus11)
8440 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8441 }
Steve Naroff61091402007-09-12 14:07:44 +00008442 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008443
Sebastian Redla9351792012-02-11 23:51:47 +00008444 // We will represent direct-initialization similarly to copy-initialization:
8445 // int x(1); -as-> int x = 1;
8446 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8447 //
8448 // Clients that want to distinguish between the two forms, can check for
8449 // direct initializer using VarDecl::getInitStyle().
8450 // A major benefit is that clients that don't particularly care about which
8451 // exactly form was it (like the CodeGen) can handle both cases without
8452 // special case code.
8453
8454 // C++ 8.5p11:
8455 // The form of initialization (using parentheses or '=') is generally
8456 // insignificant, but does matter when the entity being initialized has a
8457 // class type.
8458 if (CXXDirectInit) {
8459 assert(DirectInit && "Call-style initializer must be direct init.");
8460 VDecl->setInitStyle(VarDecl::CallInit);
8461 } else if (DirectInit) {
8462 // This must be list-initialization. No other way is direct-initialization.
8463 VDecl->setInitStyle(VarDecl::ListInit);
8464 }
8465
John McCall8b7fd8f12011-01-19 11:48:09 +00008466 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008467}
8468
John McCalleae5acb2010-03-31 02:13:20 +00008469/// ActOnInitializerError - Given that there was an error parsing an
8470/// initializer for the given declaration, try to return to some form
8471/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008472void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008473 // Our main concern here is re-establishing invariants like "a
8474 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008475 if (!D || D->isInvalidDecl()) return;
8476
8477 VarDecl *VD = dyn_cast<VarDecl>(D);
8478 if (!VD) return;
8479
Richard Smith30482bc2011-02-20 03:19:35 +00008480 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008481 if (ParsingInitForAutoVars.count(D)) {
8482 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008483 return;
8484 }
8485
John McCalleae5acb2010-03-31 02:13:20 +00008486 QualType Ty = VD->getType();
8487 if (Ty->isDependentType()) return;
8488
8489 // Require a complete type.
8490 if (RequireCompleteType(VD->getLocation(),
8491 Context.getBaseElementType(Ty),
8492 diag::err_typecheck_decl_incomplete_type)) {
8493 VD->setInvalidDecl();
8494 return;
8495 }
8496
8497 // Require an abstract type.
8498 if (RequireNonAbstractType(VD->getLocation(), Ty,
8499 diag::err_abstract_type_in_decl,
8500 AbstractVariableType)) {
8501 VD->setInvalidDecl();
8502 return;
8503 }
8504
8505 // Don't bother complaining about constructors or destructors,
8506 // though.
8507}
8508
John McCall48871652010-08-21 09:40:31 +00008509void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008510 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008511 // If there is no declaration, there was an error parsing it. Just ignore it.
8512 if (RealDecl == 0)
8513 return;
8514
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008515 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8516 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008517
Richard Smithf0215fe2011-12-25 21:17:58 +00008518 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008519 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008520 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8521 << Var->getDeclName() << Type;
8522 Var->setInvalidDecl();
8523 return;
8524 }
Mike Stump11289f42009-09-09 15:08:12 +00008525
Richard Smithf0215fe2011-12-25 21:17:58 +00008526 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008527 // the constexpr specifier; if so, its declaration shall specify
8528 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008529 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8530 // the definition of a variable [...] or the declaration of a static data
8531 // member.
8532 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8533 if (Var->isStaticDataMember())
8534 Diag(Var->getLocation(),
8535 diag::err_constexpr_static_mem_var_requires_init)
8536 << Var->getDeclName();
8537 else
8538 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008539 Var->setInvalidDecl();
8540 return;
8541 }
8542
Joey Gouly96b94e62014-01-03 14:16:55 +00008543 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8544 // be initialized.
8545 if (!Var->isInvalidDecl() &&
8546 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
8547 !Var->getInit()) {
8548 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8549 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()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00008898 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00008899 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)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009133 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009134 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,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00009346 PrevSpec, DiagID, Context.getPrintingPolicy());
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>();
Aaron Ballman9ead1242013-12-19 02:39:40 +00009631 if (DA && (!FD->hasAttr<DLLExportAttr>())) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009632 // 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)
Aaron Ballman3e424b52013-12-26 18:30:57 +00009638 << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009639 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)
Aaron Ballman44ebc072014-01-02 22:29:41 +00009651 << FD << DA;
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,
Alp Tokerd4733632013-12-05 04:47:09 +00009778 // 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 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009817 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9818 const ObjCMethodDecl *InitMethod = 0;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00009819 bool isDesignated =
9820 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009821 assert(isDesignated && InitMethod);
9822 (void)isDesignated;
9823 Diag(MD->getLocation(),
9824 diag::warn_objc_designated_init_missing_super_call);
9825 Diag(InitMethod->getLocation(),
9826 diag::note_objc_designated_init_marked_here);
9827 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9828 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009829 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9830 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9831 getCurFunction()->ObjCWarnForNoInitDelegation = false;
9832 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009833 } else {
John McCall48871652010-08-21 09:40:31 +00009834 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009835 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009836
Jordan Rose2afd6612012-10-19 16:05:26 +00009837 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009838 "This should only be set for ObjC methods, which should have been "
9839 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00009840
Chris Lattnere2473062007-05-28 06:28:18 +00009841 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00009842 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009843 // C++ constructors that have function-try-blocks can't have return
9844 // statements in the handlers of that block. (C++ [except.handle]p14)
9845 // Verify this.
9846 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9847 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9848
Richard Smithdef8bdb2011-08-12 18:44:32 +00009849 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00009850 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00009851 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009852 !hasAnyUnrecoverableErrorsInThisFunction() &&
9853 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00009854 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00009855
John McCalldeb646e2010-08-04 01:04:25 +00009856 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9857 if (!Destructor->getParent()->isDependentType())
9858 CheckDestructor(Destructor);
9859
John McCalla6309952010-03-16 21:39:52 +00009860 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9861 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00009862 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00009863
9864 // If any errors have occurred, clear out any temporaries that may have
9865 // been leftover. This ensures that these temporaries won't be picked up for
9866 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00009867 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00009868 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00009869 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00009870 }
9871 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9872 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00009873 // Since the body is valid, issue any analysis-based warnings that are
9874 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00009875 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00009876 }
9877
Richard Smith3607ffe2012-02-13 03:54:03 +00009878 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9879 (!CheckConstexprFunctionDecl(FD) ||
9880 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00009881 FD->setInvalidDecl();
9882
John McCall28fc7092011-11-10 05:35:25 +00009883 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00009884 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00009885 assert(MaybeODRUseExprs.empty() &&
9886 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00009887 }
9888
John McCalle99d5f32010-03-25 22:08:03 +00009889 if (!IsInstantiation)
9890 PopDeclContext();
9891
Eli Friedman71c80552012-01-05 03:35:19 +00009892 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +00009893 // If any errors have occurred, clear out any temporaries that may have
9894 // been leftover. This ensures that these temporaries won't be picked up for
9895 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00009896 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00009897 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00009898 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00009899
John McCall48871652010-08-21 09:40:31 +00009900 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00009901}
9902
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009903
9904/// When we finish delayed parsing of an attribute, we must attach it to the
9905/// relevant Decl.
9906void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9907 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00009908 // Always attach attributes to the underlying decl.
9909 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9910 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00009911 ProcessDeclAttributeList(S, D, Attrs.getList());
9912
9913 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9914 if (Method->isStatic())
9915 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009916}
9917
9918
Chris Lattnerac18be92006-11-20 06:49:47 +00009919/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9920/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00009921NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00009922 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009923 // Before we produce a declaration for an implicitly defined
9924 // function, see whether there was a locally-scoped declaration of
9925 // this name as a function or variable. If so, use that
9926 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +00009927 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9928 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9929 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9930 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009931 }
9932
Chris Lattner00e26072008-05-05 21:18:06 +00009933 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00009934 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00009935 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00009936 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009937 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00009938 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00009939 else
Hans Wennborg70a13242011-12-08 15:56:07 +00009940 diag_id = diag::warn_implicit_function_decl;
9941 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00009942
Hans Wennborg70a13242011-12-08 15:56:07 +00009943 // Because typo correction is expensive, only do it if the implicit
9944 // function declaration is going to be treated as an error.
9945 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9946 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00009947 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00009948 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smithf9b15102013-08-17 00:46:16 +00009949 LookupOrdinaryName, S, 0, Validator)))
9950 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9951 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +00009952 }
9953
Chris Lattnerac18be92006-11-20 06:49:47 +00009954 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00009955 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00009956 AttributeFactory attrFactory;
9957 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00009958 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00009959 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
9960 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009961 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00009962 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009963 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +00009964 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009965 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9966 /*IsAmbiguous=*/false,
9967 /*RParenLoc=*/NoLoc,
9968 /*ArgInfo=*/0,
9969 /*NumArgs=*/0,
9970 /*EllipsisLoc=*/NoLoc,
9971 /*RParenLoc=*/NoLoc,
9972 /*TypeQuals=*/0,
9973 /*RefQualifierIsLvalueRef=*/true,
9974 /*RefQualifierLoc=*/NoLoc,
9975 /*ConstQualifierLoc=*/NoLoc,
9976 /*VolatileQualifierLoc=*/NoLoc,
9977 /*MutableLoc=*/NoLoc,
9978 EST_None,
9979 /*ESpecLoc=*/NoLoc,
9980 /*Exceptions=*/0,
9981 /*ExceptionRanges=*/0,
9982 /*NumExceptions=*/0,
9983 /*NoexceptExpr=*/0,
9984 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00009985 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009986 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00009987 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009988
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00009989 // Insert this function into translation-unit scope.
9990
9991 DeclContext *PrevDC = CurContext;
9992 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009993
Jordan Rosed03d99d2013-03-05 01:27:54 +00009994 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00009995 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00009996
9997 CurContext = PrevDC;
9998
Douglas Gregore711f702009-02-14 18:57:46 +00009999 AddKnownFunctionAttributes(FD);
10000
Steve Naroff3913ea42008-04-04 14:32:09 +000010001 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010002}
10003
Douglas Gregore711f702009-02-14 18:57:46 +000010004/// \brief Adds any function attributes that we know a priori based on
10005/// the declaration of this function.
10006///
10007/// These attributes can apply both to implicitly-declared builtins
10008/// (like __builtin___printf_chk) or to library-declared functions
10009/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010010///
10011/// We need to check for duplicate attributes both here and where user-written
10012/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010013void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10014 if (FD->isInvalidDecl())
10015 return;
10016
10017 // If this is a built-in function, map its builtin attributes to
10018 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010019 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010020 // Handle printf-formatting attributes.
10021 unsigned FormatIdx;
10022 bool HasVAListArg;
10023 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010024 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010025 const char *fmt = "printf";
10026 unsigned int NumParams = FD->getNumParams();
10027 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10028 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10029 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010030 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010031 &Context.Idents.get(fmt),
10032 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010033 HasVAListArg ? 0 : FormatIdx+2,
10034 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010035 }
Douglas Gregore711f702009-02-14 18:57:46 +000010036 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010037 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10038 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010039 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010040 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010041 &Context.Idents.get("scanf"),
10042 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010043 HasVAListArg ? 0 : FormatIdx+2,
10044 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010045 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010046
10047 // Mark const if we don't care about errno and that is the only
10048 // thing preventing the function from being const. This allows
10049 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010050 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010051 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010052 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010053 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010054 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010055
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010056 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010057 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010058 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10059 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010060 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010061 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010062 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010063 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010064 }
10065
10066 IdentifierInfo *Name = FD->getIdentifier();
10067 if (!Name)
10068 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010069 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010070 FD->getDeclContext()->isTranslationUnit()) ||
10071 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010072 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010073 LinkageSpecDecl::lang_c)) {
10074 // Okay: this could be a libc/libm/Objective-C function we know
10075 // about.
10076 } else
10077 return;
10078
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010079 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010080 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010081 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010082 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010083 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010084 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010085 Name->isStr("vasprintf") ? 0 : 3,
10086 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010087 }
Jordan Rose742c6072012-08-08 21:17:31 +000010088
10089 if (Name->isStr("__CFStringMakeConstantString")) {
10090 // We already have a __builtin___CFStringMakeConstantString,
10091 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010092 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010093 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10094 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010095 }
Douglas Gregore711f702009-02-14 18:57:46 +000010096}
Chris Lattner302b4be2006-11-19 02:31:38 +000010097
John McCall703a3f82009-10-24 08:00:42 +000010098TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010099 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010100 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010101 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010102
John McCallbcd03502009-12-07 02:54:59 +000010103 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010104 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010105 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010106 }
10107
Chris Lattner18b19622007-01-22 07:39:13 +000010108 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010109 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010110 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010111 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010112 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010113 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010114
John McCall04fcd0d2011-02-01 08:20:08 +000010115 // Bail out immediately if we have an invalid declaration.
10116 if (D.isInvalidType()) {
10117 NewTD->setInvalidDecl();
10118 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010119 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010120
Douglas Gregor41866812011-09-12 18:37:38 +000010121 if (D.getDeclSpec().isModulePrivateSpecified()) {
10122 if (CurContext->isFunctionOrMethod())
10123 Diag(NewTD->getLocation(), diag::err_module_private_local)
10124 << 2 << NewTD->getDeclName()
10125 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10126 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10127 else
10128 NewTD->setModulePrivate();
10129 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010130
John McCall04fcd0d2011-02-01 08:20:08 +000010131 // C++ [dcl.typedef]p8:
10132 // If the typedef declaration defines an unnamed class (or
10133 // enum), the first typedef-name declared by the declaration
10134 // to be that class type (or enum type) is used to denote the
10135 // class type (or enum type) for linkage purposes only.
10136 // We need to check whether the type was declared in the declaration.
10137 switch (D.getDeclSpec().getTypeSpecType()) {
10138 case TST_enum:
10139 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010140 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010141 case TST_union:
10142 case TST_class: {
10143 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10144
10145 // Do nothing if the tag is not anonymous or already has an
10146 // associated typedef (from an earlier typedef in this decl group).
10147 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010148 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010149
10150 // A well-formed anonymous tag must always be a TUK_Definition.
10151 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10152
10153 // The type must match the tag exactly; no qualifiers allowed.
10154 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10155 break;
10156
10157 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010158 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010159 break;
10160 }
10161
10162 default:
10163 break;
10164 }
10165
Steve Narofff93b6722007-08-28 20:14:24 +000010166 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010167}
10168
Douglas Gregord9034f02009-05-14 16:41:31 +000010169
Richard Smith4b38ded2012-03-14 23:13:10 +000010170/// \brief Check that this is a valid underlying type for an enum declaration.
10171bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10172 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10173 QualType T = TI->getType();
10174
Eli Friedman52f32b92012-12-18 02:37:32 +000010175 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010176 return false;
10177
Eli Friedman52f32b92012-12-18 02:37:32 +000010178 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10179 if (BT->isInteger())
10180 return false;
10181
Richard Smith4b38ded2012-03-14 23:13:10 +000010182 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10183 return true;
10184}
10185
10186/// Check whether this is a valid redeclaration of a previous enumeration.
10187/// \return true if the redeclaration was invalid.
10188bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10189 QualType EnumUnderlyingTy,
10190 const EnumDecl *Prev) {
10191 bool IsFixed = !EnumUnderlyingTy.isNull();
10192
10193 if (IsScoped != Prev->isScoped()) {
10194 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10195 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010196 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010197 return true;
10198 }
10199
10200 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010201 if (!EnumUnderlyingTy->isDependentType() &&
10202 !Prev->getIntegerType()->isDependentType() &&
10203 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010204 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010205 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010206 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10207 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010208 Diag(Prev->getLocation(), diag::note_previous_declaration)
10209 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010210 return true;
10211 }
10212 } else if (IsFixed != Prev->isFixed()) {
10213 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10214 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010215 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010216 return true;
10217 }
10218
10219 return false;
10220}
10221
Joao Matosdc86f942012-08-31 18:45:21 +000010222/// \brief Get diagnostic %select index for tag kind for
10223/// redeclaration diagnostic message.
10224/// WARNING: Indexes apply to particular diagnostics only!
10225///
10226/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010227static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010228 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010229 case TTK_Struct: return 0;
10230 case TTK_Interface: return 1;
10231 case TTK_Class: return 2;
10232 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010233 }
Joao Matosdc86f942012-08-31 18:45:21 +000010234}
10235
10236/// \brief Determine if tag kind is a class-key compatible with
10237/// class for redeclaration (class, struct, or __interface).
10238///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010239/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010240static bool isClassCompatTagKind(TagTypeKind Tag)
10241{
10242 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10243}
10244
Douglas Gregord9034f02009-05-14 16:41:31 +000010245/// \brief Determine whether a tag with a given kind is acceptable
10246/// as a redeclaration of the given tag declaration.
10247///
10248/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010249bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010250 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010251 SourceLocation NewTagLoc,
10252 const IdentifierInfo &Name) {
10253 // C++ [dcl.type.elab]p3:
10254 // The class-key or enum keyword present in the
10255 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010256 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010257 // refers. This rule also applies to the form of
10258 // elaborated-type-specifier that declares a class-name or
10259 // friend class since it can be construed as referring to the
10260 // definition of the class. Thus, in any
10261 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010262 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010263 // used to refer to a union (clause 9), and either the class or
10264 // struct class-key shall be used to refer to a class (clause 9)
10265 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010266 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010267 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010268 if (OldTag == NewTag)
10269 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010270
Joao Matosdc86f942012-08-31 18:45:21 +000010271 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010272 // Warn about the struct/class tag mismatch.
10273 bool isTemplate = false;
10274 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10275 isTemplate = Record->getDescribedClassTemplate();
10276
Richard Trieucaa33d32011-06-10 03:11:26 +000010277 if (!ActiveTemplateInstantiations.empty()) {
10278 // In a template instantiation, do not offer fix-its for tag mismatches
10279 // since they usually mess up the template instead of fixing the problem.
10280 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010281 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10282 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010283 return true;
10284 }
10285
10286 if (isDefinition) {
10287 // On definitions, check previous tags and issue a fix-it for each
10288 // one that doesn't match the current tag.
10289 if (Previous->getDefinition()) {
10290 // Don't suggest fix-its for redefinitions.
10291 return true;
10292 }
10293
10294 bool previousMismatch = false;
10295 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10296 E(Previous->redecls_end()); I != E; ++I) {
10297 if (I->getTagKind() != NewTag) {
10298 if (!previousMismatch) {
10299 previousMismatch = true;
10300 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010301 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10302 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010303 }
10304 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010305 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010306 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010307 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010308 }
10309 }
10310 return true;
10311 }
10312
10313 // Check for a previous definition. If current tag and definition
10314 // are same type, do nothing. If no definition, but disagree with
10315 // with previous tag type, give a warning, but no fix-it.
10316 const TagDecl *Redecl = Previous->getDefinition() ?
10317 Previous->getDefinition() : Previous;
10318 if (Redecl->getTagKind() == NewTag) {
10319 return true;
10320 }
10321
Douglas Gregord9034f02009-05-14 16:41:31 +000010322 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010323 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10324 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010325 Diag(Redecl->getLocation(), diag::note_previous_use);
10326
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010327 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010328 if (Previous->getDefinition()) {
10329 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010330 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010331 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010332 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010333 }
10334
Douglas Gregord9034f02009-05-14 16:41:31 +000010335 return true;
10336 }
10337 return false;
10338}
10339
Steve Naroff30d242c2007-09-15 18:49:24 +000010340/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010341/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010342/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010343/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000010344///
10345/// IsTypeSpecifier is true if this is a type-specifier (or
10346/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000010347Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010348 SourceLocation KWLoc, CXXScopeSpec &SS,
10349 IdentifierInfo *Name, SourceLocation NameLoc,
10350 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010351 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010352 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010353 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010354 SourceLocation ScopedEnumKWLoc,
10355 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000010356 TypeResult UnderlyingType,
10357 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010358 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010359 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010360 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010361 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010362 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010363
Douglas Gregord6ab8742009-05-28 23:31:59 +000010364 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010365 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010366 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010367
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010368 // FIXME: Check explicit specializations more carefully.
10369 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010370 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010371
10372 // We only need to do this matching if we have template parameters
10373 // or a scope specifier, which also conveniently avoids this work
10374 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010375 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010376 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010377 if (TemplateParameterList *TemplateParams =
10378 MatchTemplateParametersToScopeSpecifier(
10379 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10380 isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010381 if (Kind == TTK_Enum) {
10382 Diag(KWLoc, diag::err_enum_template);
10383 return 0;
10384 }
10385
Douglas Gregor3dad8422009-09-26 06:47:28 +000010386 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010387 // This is a declaration or definition of a class template (which may
10388 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010389
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010390 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010391 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010392
Douglas Gregore93e46c2009-07-22 23:48:44 +000010393 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010394 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010395 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010396 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010397 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010398 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010399 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010400 return Result.get();
10401 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010402 // The "template<>" header is extraneous.
10403 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010404 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010405 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010406 }
Mike Stump11289f42009-09-09 15:08:12 +000010407 }
10408 }
10409
Douglas Gregor0bf31402010-10-08 23:50:27 +000010410 // Figure out the underlying type if this a enum declaration. We need to do
10411 // this early, because it's needed to detect if this is an incompatible
10412 // redeclaration.
10413 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10414
10415 if (Kind == TTK_Enum) {
10416 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10417 // No underlying type explicitly specified, or we failed to parse the
10418 // type, default to int.
10419 EnumUnderlying = Context.IntTy.getTypePtr();
10420 else if (UnderlyingType.get()) {
10421 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10422 // integral type; any cv-qualification is ignored.
10423 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010424 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010425 EnumUnderlying = TI;
10426
Richard Smith4b38ded2012-03-14 23:13:10 +000010427 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010428 // Recover by falling back to int.
10429 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010430
Richard Smith4b38ded2012-03-14 23:13:10 +000010431 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010432 UPPC_FixedUnderlyingType))
10433 EnumUnderlying = Context.IntTy.getTypePtr();
10434
Alp Tokerbfa39342014-01-14 12:51:41 +000010435 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000010436 // Microsoft enums are always of int type.
10437 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010438 }
10439
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010440 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010441 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010442 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010443
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010444 RedeclarationKind Redecl = ForRedeclaration;
10445 if (TUK == TUK_Friend || TUK == TUK_Reference)
10446 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010447
10448 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010449 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010450 if (Name && SS.isNotEmpty()) {
10451 // We have a nested-name tag ('struct foo::bar').
10452
10453 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010454 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010455 Name = 0;
10456 goto CreateNewDecl;
10457 }
10458
John McCall7f41d982009-09-11 04:59:25 +000010459 // If this is a friend or a reference to a class in a dependent
10460 // context, don't try to make a decl for it.
10461 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10462 DC = computeDeclContext(SS, false);
10463 if (!DC) {
10464 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010465 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010466 }
John McCall0b66eb32010-05-01 00:40:08 +000010467 } else {
10468 DC = computeDeclContext(SS, true);
10469 if (!DC) {
10470 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10471 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010472 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010473 }
John McCall7f41d982009-09-11 04:59:25 +000010474 }
10475
John McCall0b66eb32010-05-01 00:40:08 +000010476 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010477 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010478
Douglas Gregor8761da52009-02-03 00:34:39 +000010479 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010480 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010481 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010482
John McCall1f82f242009-11-18 22:49:29 +000010483 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010484 return 0;
John McCall6538c932009-10-10 05:48:19 +000010485
John McCall1f82f242009-11-18 22:49:29 +000010486 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010487 // Name lookup did not find anything. However, if the
10488 // nested-name-specifier refers to the current instantiation,
10489 // and that current instantiation has any dependent base
10490 // classes, we might find something at instantiation time: treat
10491 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010492 // But this only makes any sense for reference-like lookups.
10493 if (Previous.wasNotFoundInCurrentInstantiation() &&
10494 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010495 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010496 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010497 }
10498
10499 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010500 Diag(NameLoc, diag::err_not_tag_in_scope)
10501 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010502 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010503 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010504 goto CreateNewDecl;
10505 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010506 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010507 // If this is a named struct, check to see if there was a previous forward
10508 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010509 // FIXME: We're looking into outer scopes here, even when we
10510 // shouldn't be. Doing so can result in ambiguities that we
10511 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010512 LookupName(Previous, S);
10513
John McCall3c581bf2013-03-20 01:53:00 +000010514 // When declaring or defining a tag, ignore ambiguities introduced
10515 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010516 if (Previous.isAmbiguous() &&
10517 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010518 LookupResult::Filter F = Previous.makeFilter();
10519 while (F.hasNext()) {
10520 NamedDecl *ND = F.next();
10521 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10522 F.erase();
10523 }
10524 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010525 }
John McCall3c581bf2013-03-20 01:53:00 +000010526
10527 // C++11 [namespace.memdef]p3:
10528 // If the name in a friend declaration is neither qualified nor
10529 // a template-id and the declaration is a function or an
10530 // elaborated-type-specifier, the lookup to determine whether
10531 // the entity has been previously declared shall not consider
10532 // any scopes outside the innermost enclosing namespace.
10533 //
10534 // Does it matter that this should be by scope instead of by
10535 // semantic context?
10536 if (!Previous.empty() && TUK == TUK_Friend) {
10537 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10538 LookupResult::Filter F = Previous.makeFilter();
10539 while (F.hasNext()) {
10540 NamedDecl *ND = F.next();
10541 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010542 if (DC->isFileContext() &&
10543 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010544 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010545 FriendSawTagOutsideEnclosingNamespace = true;
10546 }
John McCall3c581bf2013-03-20 01:53:00 +000010547 }
10548 F.done();
10549 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010550
John McCall1f82f242009-11-18 22:49:29 +000010551 // Note: there used to be some attempt at recovery here.
10552 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010553 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010554
David Blaikiebbafb8a2012-03-11 07:00:24 +000010555 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010556 // FIXME: This makes sure that we ignore the contexts associated
10557 // with C structs, unions, and enums when looking for a matching
10558 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010559 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010560 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10561 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010562 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010563 } else if (S->isFunctionPrototypeScope()) {
10564 // If this is an enum declaration in function prototype scope, set its
10565 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010566 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010567 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010568 }
10569
John McCall1f82f242009-11-18 22:49:29 +000010570 if (Previous.isSingleResult() &&
10571 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010572 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010573 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010574 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010575 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010576 }
10577
David Blaikiebbafb8a2012-03-11 07:00:24 +000010578 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010579 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010580 // This is a declaration of or a reference to "std::bad_alloc".
10581 isStdBadAlloc = true;
10582
John McCall1f82f242009-11-18 22:49:29 +000010583 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010584 // std::bad_alloc has been implicitly declared (but made invisible to
10585 // name lookup). Fill in this implicit declaration as the previous
10586 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010587 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010588 }
10589 }
John McCall1f82f242009-11-18 22:49:29 +000010590
John McCalle9eaf8e2010-03-25 21:28:06 +000010591 // If we didn't find a previous declaration, and this is a reference
10592 // (or friend reference), move to the correct scope. In C++, we
10593 // also need to do a redeclaration lookup there, just in case
10594 // there's a shadow friend decl.
10595 if (Name && Previous.empty() &&
10596 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10597 if (Invalid) goto CreateNewDecl;
10598 assert(SS.isEmpty());
10599
10600 if (TUK == TUK_Reference) {
10601 // C++ [basic.scope.pdecl]p5:
10602 // -- for an elaborated-type-specifier of the form
10603 //
10604 // class-key identifier
10605 //
10606 // if the elaborated-type-specifier is used in the
10607 // decl-specifier-seq or parameter-declaration-clause of a
10608 // function defined in namespace scope, the identifier is
10609 // declared as a class-name in the namespace that contains
10610 // the declaration; otherwise, except as a friend
10611 // declaration, the identifier is declared in the smallest
10612 // non-class, non-function-prototype scope that contains the
10613 // declaration.
10614 //
10615 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10616 // C structs and unions.
10617 //
10618 // It is an error in C++ to declare (rather than define) an enum
10619 // type, including via an elaborated type specifier. We'll
10620 // diagnose that later; for now, declare the enum in the same
10621 // scope as we would have picked for any other tag type.
10622 //
10623 // GNU C also supports this behavior as part of its incomplete
10624 // enum types extension, while GNU C++ does not.
10625 //
10626 // Find the context where we'll be declaring the tag.
10627 // FIXME: We would like to maintain the current DeclContext as the
10628 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010629 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010630 SearchDC = SearchDC->getParent();
10631
10632 // Find the scope where we'll be declaring the tag.
10633 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010634 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010635 S->isFunctionPrototypeScope()) ||
10636 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010637 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010638 S = S->getParent();
10639 } else {
10640 assert(TUK == TUK_Friend);
10641 // C++ [namespace.memdef]p3:
10642 // If a friend declaration in a non-local class first declares a
10643 // class or function, the friend class or function is a member of
10644 // the innermost enclosing namespace.
10645 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010646 }
10647
John McCalle87beb22010-04-23 18:46:30 +000010648 // In C++, we need to do a redeclaration lookup to properly
10649 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010650 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010651 Previous.setRedeclarationKind(ForRedeclaration);
10652 LookupQualifiedName(Previous, SearchDC);
10653 }
10654 }
10655
John McCall1f82f242009-11-18 22:49:29 +000010656 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000010657 NamedDecl *PrevDecl = Previous.getFoundDecl();
10658 NamedDecl *DirectPrevDecl =
10659 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000010660
10661 // It's okay to have a tag decl in the same scope as a typedef
10662 // which hides a tag decl in the same scope. Finding this
10663 // insanity with a redeclaration lookup can only actually happen
10664 // in C++.
10665 //
10666 // This is also okay for elaborated-type-specifiers, which is
10667 // technically forbidden by the current standard but which is
10668 // okay according to the likely resolution of an open issue;
10669 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010670 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010671 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010672 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10673 TagDecl *Tag = TT->getDecl();
10674 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010675 Tag->getDeclContext()->getRedeclContext()
10676 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010677 PrevDecl = Tag;
10678 Previous.clear();
10679 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010680 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010681 }
10682 }
10683 }
10684 }
10685
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010686 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010687 // If this is a use of a previous tag, or if the tag is already declared
10688 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010689 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010690 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000010691 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000010692 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010693 // Make sure that this wasn't declared as an enum and now used as a
10694 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010695 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10696 TUK == TUK_Definition, KWLoc,
10697 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010698 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010699 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10700 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010701 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010702 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010703 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010704 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10705 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010706 else
10707 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010708 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010709
Mike Stump11289f42009-09-09 15:08:12 +000010710 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010711 Kind = PrevTagDecl->getTagKind();
10712 else {
10713 // Recover by making this an anonymous redefinition.
10714 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010715 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010716 Invalid = true;
10717 }
10718 }
10719
Douglas Gregor0bf31402010-10-08 23:50:27 +000010720 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10721 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10722
Richard Smith0f8ee222012-01-10 01:33:14 +000010723 // If this is an elaborated-type-specifier for a scoped enumeration,
10724 // the 'class' keyword is not necessary and not permitted.
10725 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10726 if (ScopedEnum)
10727 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10728 << PrevEnum->isScoped()
10729 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10730 return PrevTagDecl;
10731 }
10732
Richard Smith4b38ded2012-03-14 23:13:10 +000010733 QualType EnumUnderlyingTy;
10734 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000010735 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000010736 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10737 EnumUnderlyingTy = QualType(T, 0);
10738
Douglas Gregor0bf31402010-10-08 23:50:27 +000010739 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010740 // returning the previous declaration, unless this is a definition,
10741 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010742 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10743 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010744 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010745 }
10746
David Majnemer55890bf2013-06-11 03:51:23 +000010747 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010748 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010749 // except that a nested class or member class template can be declared
10750 // and then later defined.
10751 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10752 S->isDeclScope(PrevDecl)) {
10753 Diag(NameLoc, diag::ext_member_redeclared);
10754 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10755 }
10756
Douglas Gregor170512f2009-04-01 23:51:29 +000010757 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010758 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010759
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010760 // FIXME: In the future, return a variant or some other clue
10761 // for the consumer of this Decl to know it doesn't own it.
10762 // For our current ASTs this shouldn't be a problem, but will
10763 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010764 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010765 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010766 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010767
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010768 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010769 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010770 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010771 // If we're defining a specialization and the previous definition
10772 // is from an implicit instantiation, don't emit an error
10773 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010774 bool IsExplicitSpecializationAfterInstantiation = false;
10775 if (isExplicitSpecialization) {
10776 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10777 IsExplicitSpecializationAfterInstantiation =
10778 RD->getTemplateSpecializationKind() !=
10779 TSK_ExplicitSpecialization;
10780 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10781 IsExplicitSpecializationAfterInstantiation =
10782 ED->getTemplateSpecializationKind() !=
10783 TSK_ExplicitSpecialization;
10784 }
10785
10786 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010787 // A redeclaration in function prototype scope in C isn't
10788 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010789 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010790 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10791 else
10792 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010793 Diag(Def->getLocation(), diag::note_previous_definition);
10794 // If this is a redefinition, recover by making this
10795 // struct be anonymous, which will make any later
10796 // references get the previous definition.
10797 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010798 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010799 Invalid = true;
10800 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010801 } else {
10802 // If the type is currently being defined, complain
10803 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010804 const TagType *Tag
10805 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010806 if (Tag->isBeingDefined()) {
10807 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010808 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010809 diag::note_previous_definition);
10810 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010811 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010812 Invalid = true;
10813 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010814 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010815
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010816 // Okay, this is definition of a previously declared or referenced
10817 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010818 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010819 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010820 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000010821 // have a definition. Just create a new decl.
10822
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010823 } else {
10824 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000010825 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010826 // new decl/type. We set PrevDecl to NULL so that the entities
10827 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000010828 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000010829 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010830 // If we get here, we're going to create a new Decl. If PrevDecl
10831 // is non-NULL, it's a definition of the tag declared by
10832 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000010833
10834
10835 // Otherwise, PrevDecl is not a tag, but was found with tag
10836 // lookup. This is only actually possible in C++, where a few
10837 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010838 } else {
John McCalle87beb22010-04-23 18:46:30 +000010839 // Use a better diagnostic if an elaborated-type-specifier
10840 // found the wrong kind of type on the first
10841 // (non-redeclaration) lookup.
10842 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10843 !Previous.isForRedeclaration()) {
10844 unsigned Kind = 0;
10845 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010846 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10847 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010848 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10849 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10850 Invalid = true;
10851
10852 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000010853 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10854 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000010855 // do nothing
10856
10857 // Diagnose implicit declarations introduced by elaborated types.
10858 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10859 unsigned Kind = 0;
10860 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010861 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10862 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010863 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10864 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10865 Invalid = true;
10866
10867 // Otherwise it's a declaration. Call out a particularly common
10868 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000010869 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10870 unsigned Kind = 0;
10871 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000010872 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000010873 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000010874 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10875 Invalid = true;
10876
10877 // Otherwise, diagnose.
10878 } else {
10879 // The tag name clashes with something else in the target scope,
10880 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010881 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000010882 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010883 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000010884 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010885 }
John McCalle87beb22010-04-23 18:46:30 +000010886
10887 // The existing declaration isn't relevant to us; we're in a
10888 // new scope, so clear out the previous declaration.
10889 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000010890 }
Chris Lattner18b19622007-01-22 07:39:13 +000010891 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000010892
Chris Lattner438e5012008-12-17 07:13:27 +000010893CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000010894
John McCall1f82f242009-11-18 22:49:29 +000010895 TagDecl *PrevDecl = 0;
10896 if (Previous.isSingleResult())
10897 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10898
Chris Lattnerbf0b7982007-01-23 04:27:41 +000010899 // If there is an identifier, use the location of the identifier as the
10900 // location of the decl, otherwise use the location of the struct/union
10901 // keyword.
10902 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000010903
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010904 // Otherwise, create a new declaration. If there is a previous
10905 // declaration of the same entity, the two will be linked via
10906 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000010907 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000010908
Douglas Gregor0bf31402010-10-08 23:50:27 +000010909 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010910 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000010911 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10912 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010913 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010914 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010915 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000010916 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010917 if (TUK != TUK_Definition && !Invalid) {
10918 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000010919 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10920 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010921 // C++0x: 7.2p2: opaque-enum-declaration.
10922 // Conflicts are diagnosed above. Do nothing.
10923 }
10924 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010925 Diag(Loc, diag::ext_forward_ref_enum_def)
10926 << New;
10927 Diag(Def->getLocation(), diag::note_previous_definition);
10928 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000010929 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000010930 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000010931 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010932 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000010933 DiagID = diag::err_forward_ref_enum;
10934 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010935
10936 // If this is a forward-declared reference to an enumeration, make a
10937 // note of it; we won't actually be introducing the declaration into
10938 // the declaration context.
10939 if (TUK == TUK_Reference)
10940 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010941 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000010942 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000010943
10944 if (EnumUnderlying) {
10945 EnumDecl *ED = cast<EnumDecl>(New);
10946 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10947 ED->setIntegerTypeSourceInfo(TI);
10948 else
10949 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10950 ED->setPromotionType(ED->getIntegerType());
10951 }
10952
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000010953 } else {
10954 // struct/union/class
10955
Chris Lattner776fac82007-06-09 00:53:06 +000010956 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10957 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010958 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000010959 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010960 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010961 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010962
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010963 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000010964 StdBadAlloc = cast<CXXRecordDecl>(New);
10965 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010966 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010967 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000010968 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010969
Richard Smith649c7b062014-01-08 00:56:48 +000010970 // C++11 [dcl.type]p3:
10971 // A type-specifier-seq shall not define a class or enumeration [...].
10972 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
10973 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
10974 << Context.getTagDeclType(New);
10975 Invalid = true;
10976 }
10977
John McCall3e11ebe2010-03-15 10:12:16 +000010978 // Maybe add qualifier info.
10979 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000010980 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010981 // If this is either a declaration or a definition, check the
10982 // nested-name-specifier against the current context. We don't do this
10983 // for explicit specializations, because they have similar checking
10984 // (with more specific diagnostics) in the call to
10985 // CheckMemberSpecialization, below.
10986 if (!isExplicitSpecialization &&
10987 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10988 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10989 Invalid = true;
10990
Douglas Gregor14454802011-02-25 02:25:35 +000010991 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000010992 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000010993 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000010994 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010995 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000010996 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000010997 }
10998 else
10999 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011000 }
11001
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011002 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11003 // Add alignment attributes if necessary; these attributes are checked when
11004 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011005 //
11006 // It is important for implementing the correct semantics that this
11007 // happen here (in act on tag decl). The #pragma pack stack is
11008 // maintained as a result of parser callbacks which can occur at
11009 // many points during the parsing of a struct declaration (because
11010 // the #pragma tokens are effectively skipped over during the
11011 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011012 if (TUK == TUK_Definition) {
11013 AddAlignmentAttributesForRecord(RD);
11014 AddMsStructLayoutForRecord(RD);
11015 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011016 }
11017
Douglas Gregor21823bf2011-12-20 18:11:52 +000011018 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011019 if (isExplicitSpecialization)
11020 Diag(New->getLocation(), diag::err_module_private_specialization)
11021 << 2
11022 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011023 // __module_private__ does not apply to local classes. However, we only
11024 // diagnose this as an error when the declaration specifiers are
11025 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011026 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011027 New->setModulePrivate();
11028 }
11029
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011030 // If this is a specialization of a member class (of a class template),
11031 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011032 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011033 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011034
Douglas Gregordee1be82009-01-17 00:42:38 +000011035 if (Invalid)
11036 New->setInvalidDecl();
11037
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011038 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011039 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011040
Douglas Gregordee1be82009-01-17 00:42:38 +000011041 // If we're declaring or defining a tag in function prototype scope
11042 // in C, note that this type can only be used within the function.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011043 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor658b9552009-01-09 22:42:13 +000011044 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11045
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011046 // Set the lexical context. If the tag has a C++ scope specifier, the
11047 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011048 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011049
John McCallaa74a0c2009-08-28 07:59:38 +000011050 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011051 // In Microsoft mode, a friend declaration also acts as a forward
11052 // declaration so we always pass true to setObjectOfFriendDecl to make
11053 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011054 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011055 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11056 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011057
Anders Carlsson5558ca12009-03-26 01:19:02 +000011058 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011059 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011060 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011061
John McCall9bb74a52009-07-31 02:45:11 +000011062 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011063 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011064
Chris Lattner18b19622007-01-22 07:39:13 +000011065 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011066 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011067 // We might be replacing an existing declaration in the lookup tables;
11068 // if so, borrow its access specifier.
11069 if (PrevDecl)
11070 New->setAccess(PrevDecl->getAccess());
11071
Sebastian Redl50c68252010-08-31 00:36:30 +000011072 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011073 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011074 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011075 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11076 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011077 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011078 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011079 PushOnScopeChains(New, S, !IsForwardReference);
11080 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011081 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011082
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011083 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011084 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011085 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011086
Douglas Gregor27821ce2009-07-07 16:35:42 +000011087 // If this is the C FILE type, notify the AST context.
11088 if (IdentifierInfo *II = New->getIdentifier())
11089 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011090 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011091 II->isStr("FILE"))
11092 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011093
James Molloy6f8780b2012-02-29 10:24:19 +000011094 // If we were in function prototype scope (and not in C++ mode), add this
11095 // tag to the list of decls to inject into the function definition scope.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011096 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy6f8780b2012-02-29 10:24:19 +000011097 InFunctionDeclarator && Name)
11098 DeclsInPrototypeScope.push_back(New);
11099
Rafael Espindolac67f2232012-05-10 02:50:16 +000011100 if (PrevDecl)
11101 mergeDeclAttributes(New, PrevDecl);
11102
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011103 // If there's a #pragma GCC visibility in scope, set the visibility of this
11104 // record.
11105 AddPushedVisibilityAttribute(New);
11106
Douglas Gregord6ab8742009-05-28 23:31:59 +000011107 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011108 // In C++, don't return an invalid declaration. We can't recover well from
11109 // the cases where we make the type anonymous.
11110 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011111}
Chris Lattner1300fb92007-01-23 23:42:53 +000011112
John McCall48871652010-08-21 09:40:31 +000011113void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011114 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011115 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011116
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011117 // Enter the tag context.
11118 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011119
11120 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011121
11122 // If there's a #pragma GCC visibility in scope, set the visibility of this
11123 // record.
11124 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011125}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011126
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011127Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011128 assert(isa<ObjCContainerDecl>(IDecl) &&
11129 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11130 DeclContext *OCD = cast<DeclContext>(IDecl);
11131 assert(getContainingDC(OCD) == CurContext &&
11132 "The next DeclContext should be lexically contained in the current one.");
11133 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011134 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011135}
11136
John McCall48871652010-08-21 09:40:31 +000011137void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011138 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011139 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011140 SourceLocation LBraceLoc) {
11141 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011142 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011143
John McCall1c7e6ec2009-12-20 07:58:13 +000011144 FieldCollector->StartClass();
11145
11146 if (!Record->getIdentifier())
11147 return;
11148
Anders Carlsson30f29442011-03-25 14:31:08 +000011149 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011150 Record->addAttr(new (Context)
11151 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11152
John McCall1c7e6ec2009-12-20 07:58:13 +000011153 // C++ [class]p2:
11154 // [...] The class-name is also inserted into the scope of the
11155 // class itself; this is known as the injected-class-name. For
11156 // purposes of access checking, the injected-class-name is treated
11157 // as if it were a public member name.
11158 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011159 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11160 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011161 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011162 /*PrevDecl=*/0,
11163 /*DelayTypeCreation=*/true);
11164 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011165 InjectedClassName->setImplicit();
11166 InjectedClassName->setAccess(AS_public);
11167 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11168 InjectedClassName->setDescribedClassTemplate(Template);
11169 PushOnScopeChains(InjectedClassName, S);
11170 assert(InjectedClassName->isInjectedClassName() &&
11171 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011172}
11173
John McCall48871652010-08-21 09:40:31 +000011174void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011175 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011176 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011177 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011178 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011179
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011180 // Make sure we "complete" the definition even it is invalid.
11181 if (Tag->isBeingDefined()) {
11182 assert(Tag->isInvalidDecl() && "We should already have completed it");
11183 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11184 RD->completeDefinition();
11185 }
11186
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011187 if (isa<CXXRecordDecl>(Tag))
11188 FieldCollector->FinishClass();
11189
11190 // Exit this scope of this tag's definition.
11191 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011192
11193 if (getCurLexicalContext()->isObjCContainer() &&
11194 Tag->getDeclContext()->isFileContext())
11195 Tag->setTopLevelDeclInObjCContainer();
11196
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011197 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011198 if (!Tag->isInvalidDecl())
11199 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011200}
Chris Lattner535b8302008-06-21 19:39:06 +000011201
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011202void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011203 // Exit this scope of this interface definition.
11204 PopDeclContext();
11205}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011206
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011207void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011208 assert(DC == CurContext && "Mismatch of container contexts");
11209 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011210 ActOnObjCContainerFinishDefinition();
11211}
11212
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011213void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11214 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011215 OriginalLexicalContext = 0;
11216}
11217
John McCall48871652010-08-21 09:40:31 +000011218void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011219 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011220 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011221 Tag->setInvalidDecl();
11222
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011223 // Make sure we "complete" the definition even it is invalid.
11224 if (Tag->isBeingDefined()) {
11225 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11226 RD->completeDefinition();
11227 }
11228
John McCall71ba5f22010-03-17 19:25:57 +000011229 // We're undoing ActOnTagStartDefinition here, not
11230 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11231 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011232
11233 PopDeclContext();
11234}
11235
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011236// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011237ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11238 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011239 QualType FieldTy, bool IsMsStruct,
11240 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011241 // Default to true; that shouldn't confuse checks for emptiness
11242 if (ZeroWidth)
11243 *ZeroWidth = true;
11244
Chris Lattner73bf7b42009-03-05 22:45:59 +000011245 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011246 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011247 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011248 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011249 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011250 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011251 if (FieldName)
11252 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11253 << FieldName << FieldTy << BitWidth->getSourceRange();
11254 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11255 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011256 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11257 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011258 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011259
11260 // If the bit-width is type- or value-dependent, don't try to check
11261 // it now.
11262 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011263 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011264
Anders Carlsson5df391e2008-12-06 20:33:04 +000011265 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011266 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11267 if (ICE.isInvalid())
11268 return ICE;
11269 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011270
Eli Friedmanc96d4962009-08-15 21:55:26 +000011271 if (Value != 0 && ZeroWidth)
11272 *ZeroWidth = false;
11273
Chris Lattner81ed6802008-12-12 04:56:04 +000011274 // Zero-width bitfield is ok for anonymous field.
11275 if (Value == 0 && FieldName)
11276 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011277
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011278 if (Value.isSigned() && Value.isNegative()) {
11279 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011280 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011281 << FieldName << Value.toString(10);
11282 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11283 << Value.toString(10);
11284 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011285
Douglas Gregor1efa4372009-03-11 18:59:21 +000011286 if (!FieldTy->isDependentType()) {
11287 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011288 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011289 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11290 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011291 if (FieldName)
11292 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11293 << FieldName << (unsigned)Value.getZExtValue()
11294 << (unsigned)TypeSize;
11295
11296 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11297 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11298 }
11299
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011300 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011301 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11302 << FieldName << (unsigned)Value.getZExtValue()
11303 << (unsigned)TypeSize;
11304 else
11305 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11306 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011307 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011308 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011309
Richard Smithf4c51d92012-02-04 09:53:13 +000011310 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011311}
11312
Richard Smith938f40b2011-06-11 17:19:42 +000011313/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011314/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011315Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011316 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011317 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011318 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011319 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011320 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011321}
11322
11323/// HandleField - Analyze a field of a C struct or a C++ data member.
11324///
11325FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11326 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011327 Declarator &D, Expr *BitWidth,
11328 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011329 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011330 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011331 SourceLocation Loc = DeclStart;
11332 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011333
John McCall8cb7bdf2010-06-04 23:28:52 +000011334 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11335 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011336 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011337 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011338
Douglas Gregora02a72a2010-12-15 23:18:36 +000011339 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11340 UPPC_DataMemberType)) {
11341 D.setInvalidType();
11342 T = Context.IntTy;
11343 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11344 }
11345 }
11346
Matt Arsenault376f7202013-02-26 21:16:00 +000011347 // TR 18037 does not allow fields to be declared with address spaces.
11348 if (T.getQualifiers().hasAddressSpace()) {
11349 Diag(Loc, diag::err_field_with_address_space);
11350 D.setInvalidType();
11351 }
11352
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011353 // OpenCL 1.2 spec, s6.9 r:
11354 // The event type cannot be used to declare a structure or union field.
11355 if (LangOpts.OpenCL && T->isEventT()) {
11356 Diag(Loc, diag::err_event_t_struct_field);
11357 D.setInvalidType();
11358 }
11359
Richard Smithb1402ae2013-03-18 22:52:47 +000011360 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011361
Richard Smithb4a9e862013-04-12 22:46:28 +000011362 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11363 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11364 diag::err_invalid_thread)
11365 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011366
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011367 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011368 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011369 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11370 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011371 switch (Previous.getResultKind()) {
11372 case LookupResult::Found:
11373 case LookupResult::FoundUnresolvedValue:
11374 PrevDecl = Previous.getAsSingle<NamedDecl>();
11375 break;
11376
11377 case LookupResult::FoundOverloaded:
11378 PrevDecl = Previous.getRepresentativeDecl();
11379 break;
11380
11381 case LookupResult::NotFound:
11382 case LookupResult::NotFoundInCurrentInstantiation:
11383 case LookupResult::Ambiguous:
11384 break;
11385 }
11386 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011387
11388 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11389 // Maybe we will complain about the shadowed template parameter.
11390 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11391 // Just pretend that we didn't see the previous declaration.
11392 PrevDecl = 0;
11393 }
11394
Douglas Gregor1efa4372009-03-11 18:59:21 +000011395 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11396 PrevDecl = 0;
11397
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011398 bool Mutable
11399 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011400 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011401 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011402 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011403 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011404
11405 if (NewFD->isInvalidDecl())
11406 Record->setInvalidDecl();
11407
Douglas Gregor3baa6702011-09-12 16:11:24 +000011408 if (D.getDeclSpec().isModulePrivateSpecified())
11409 NewFD->setModulePrivate();
11410
Douglas Gregor1efa4372009-03-11 18:59:21 +000011411 if (NewFD->isInvalidDecl() && PrevDecl) {
11412 // Don't introduce NewFD into scope; there's already something
11413 // with the same name in the same scope.
11414 } else if (II) {
11415 PushOnScopeChains(NewFD, S);
11416 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011417 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011418
11419 return NewFD;
11420}
11421
11422/// \brief Build a new FieldDecl and check its well-formedness.
11423///
11424/// This routine builds a new FieldDecl given the fields name, type,
11425/// record, etc. \p PrevDecl should refer to any previous declaration
11426/// with the same name and in the same scope as the field to be
11427/// created.
11428///
11429/// \returns a new FieldDecl.
11430///
Mike Stump11289f42009-09-09 15:08:12 +000011431/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011432FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011433 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011434 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011435 bool Mutable, Expr *BitWidth,
11436 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011437 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011438 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011439 Declarator *D) {
11440 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011441 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011442 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011443
Douglas Gregor1efa4372009-03-11 18:59:21 +000011444 // If we receive a broken type, recover by assuming 'int' and
11445 // marking this declaration as invalid.
11446 if (T.isNull()) {
11447 InvalidDecl = true;
11448 T = Context.IntTy;
11449 }
11450
Eli Friedmand0e8de22009-12-07 00:22:08 +000011451 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011452 if (!EltTy->isDependentType()) {
11453 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11454 // Fields of incomplete type force their record to be invalid.
11455 Record->setInvalidDecl();
11456 InvalidDecl = true;
11457 } else {
11458 NamedDecl *Def;
11459 EltTy->isIncompleteType(&Def);
11460 if (Def && Def->isInvalidDecl()) {
11461 Record->setInvalidDecl();
11462 InvalidDecl = true;
11463 }
11464 }
John McCall2677e102010-08-16 23:42:35 +000011465 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011466
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011467 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11468 if (BitWidth && getLangOpts().OpenCL) {
11469 Diag(Loc, diag::err_opencl_bitfields);
11470 InvalidDecl = true;
11471 }
11472
Steve Naroff8eeeb132007-05-08 21:09:37 +000011473 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11474 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011475 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011476 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011477 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011478
11479 TypeSourceInfo *FixedTInfo =
11480 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11481 SizeIsNegative,
11482 Oversized);
11483 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011484 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011485 TInfo = FixedTInfo;
11486 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011487 } else {
11488 if (SizeIsNegative)
11489 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011490 else if (Oversized.getBoolValue())
11491 Diag(Loc, diag::err_array_too_large)
11492 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011493 else
11494 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011495 InvalidDecl = true;
11496 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011497 }
Mike Stump11289f42009-09-09 15:08:12 +000011498
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011499 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011500 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11501 diag::err_abstract_type_in_decl,
11502 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011503 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011504
Eli Friedmanc96d4962009-08-15 21:55:26 +000011505 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011506 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011507 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011508 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11509 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011510 if (!BitWidth) {
11511 InvalidDecl = true;
11512 BitWidth = 0;
11513 ZeroWidth = false;
11514 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011515 }
Mike Stump11289f42009-09-09 15:08:12 +000011516
John McCallb1cd7da2010-06-04 08:34:12 +000011517 // Check that 'mutable' is consistent with the type of the declaration.
11518 if (!InvalidDecl && Mutable) {
11519 unsigned DiagID = 0;
11520 if (T->isReferenceType())
11521 DiagID = diag::err_mutable_reference;
11522 else if (T.isConstQualified())
11523 DiagID = diag::err_mutable_const;
11524
11525 if (DiagID) {
11526 SourceLocation ErrLoc = Loc;
11527 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11528 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11529 Diag(ErrLoc, DiagID);
11530 Mutable = false;
11531 InvalidDecl = true;
11532 }
11533 }
11534
Richard Smithab44d5b2013-12-10 08:25:00 +000011535 // C++11 [class.union]p8 (DR1460):
11536 // At most one variant member of a union may have a
11537 // brace-or-equal-initializer.
11538 if (InitStyle != ICIS_NoInit)
11539 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11540
Abramo Bagnaradff19302011-03-08 08:55:46 +000011541 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011542 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011543 if (InvalidDecl)
11544 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011545
Douglas Gregor1efa4372009-03-11 18:59:21 +000011546 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11547 Diag(Loc, diag::err_duplicate_member) << II;
11548 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11549 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011550 }
11551
David Blaikiebbafb8a2012-03-11 07:00:24 +000011552 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011553 if (Record->isUnion()) {
11554 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11555 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11556 if (RDecl->getDefinition()) {
11557 // C++ [class.union]p1: An object of a class with a non-trivial
11558 // constructor, a non-trivial copy constructor, a non-trivial
11559 // destructor, or a non-trivial copy assignment operator
11560 // cannot be a member of a union, nor can an array of such
11561 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011562 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011563 NewFD->setInvalidDecl();
11564 }
11565 }
11566
11567 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011568 // the program is ill-formed, except when compiling with MSVC extensions
11569 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011570 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011571 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11572 diag::ext_union_member_of_reference_type :
11573 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011574 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011575 if (!getLangOpts().MicrosoftExt)
11576 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011577 }
11578 }
11579 }
11580
Douglas Gregor1efa4372009-03-11 18:59:21 +000011581 // FIXME: We need to pass in the attributes given an AST
11582 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011583 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011584 // FIXME: The current scope is almost... but not entirely... correct here.
11585 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011586
Richard Smith848e1f12013-02-01 08:12:08 +000011587 if (NewFD->hasAttrs())
11588 CheckAlignasUnderalignment(NewFD);
11589 }
11590
John McCall31168b02011-06-15 23:02:42 +000011591 // In auto-retain/release, infer strong retension for fields of
11592 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011593 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011594 NewFD->setInvalidDecl();
11595
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011596 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011597 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011598
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011599 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011600 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011601}
11602
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011603bool Sema::CheckNontrivialField(FieldDecl *FD) {
11604 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011605 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011606
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011607 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11608 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011609
11610 QualType EltTy = Context.getBaseElementType(FD->getType());
11611 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011612 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011613 if (RDecl->getDefinition()) {
11614 // We check for copy constructors before constructors
11615 // because otherwise we'll never get complaints about
11616 // copy constructors.
11617
11618 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011619 // We're required to check for any non-trivial constructors. Since the
11620 // implicit default constructor is suppressed if there are any
11621 // user-declared constructors, we just need to check that there is a
11622 // trivial default constructor and a trivial copy constructor. (We don't
11623 // worry about move constructors here, since this is a C++98 check.)
11624 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011625 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011626 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011627 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011628 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011629 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011630 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011631 member = CXXDestructor;
11632
11633 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011634 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011635 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011636 // Objective-C++ ARC: it is an error to have a non-trivial field of
11637 // a union. However, system headers in Objective-C programs
11638 // occasionally have Objective-C lifetime objects within unions,
11639 // and rather than cause the program to fail, we make those
11640 // members unavailable.
11641 SourceLocation Loc = FD->getLocation();
11642 if (getSourceManager().isInSystemHeader(Loc)) {
11643 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000011644 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11645 "this system field has retaining ownership",
11646 Loc));
John McCall31168b02011-06-15 23:02:42 +000011647 return false;
11648 }
11649 }
Richard Smithf720df02011-10-19 20:41:51 +000011650
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011651 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011652 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11653 diag::err_illegal_union_or_anon_struct_member)
11654 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011655 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011656 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011657 }
11658 }
11659 }
Richard Smith92f241f2012-12-08 02:53:02 +000011660
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011661 return false;
11662}
11663
Mike Stump11289f42009-09-09 15:08:12 +000011664/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011665/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011666static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011667TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011668 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011669 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011670 case tok::objc_private: return ObjCIvarDecl::Private;
11671 case tok::objc_public: return ObjCIvarDecl::Public;
11672 case tok::objc_protected: return ObjCIvarDecl::Protected;
11673 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011674 }
11675}
11676
Mike Stump11289f42009-09-09 15:08:12 +000011677/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011678/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011679Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011680 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011681 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011682 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011683
Fariborz Jahaniande615832008-04-10 23:32:45 +000011684 IdentifierInfo *II = D.getIdentifier();
11685 Expr *BitWidth = (Expr*)BitfieldWidth;
11686 SourceLocation Loc = DeclStart;
11687 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011688
Fariborz Jahaniande615832008-04-10 23:32:45 +000011689 // FIXME: Unnamed fields can be handled in various different ways, for
11690 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011691
John McCall8cb7bdf2010-06-04 23:28:52 +000011692 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11693 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011694
Fariborz Jahaniande615832008-04-10 23:32:45 +000011695 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011696 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011697 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011698 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011699 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011700 } else {
11701 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011702
Fariborz Jahaniande615832008-04-10 23:32:45 +000011703 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011704
Fariborz Jahaniande615832008-04-10 23:32:45 +000011705 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011706 if (T->isReferenceType()) {
11707 Diag(Loc, diag::err_ivar_reference_type);
11708 D.setInvalidType();
11709 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011710 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11711 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011712 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011713 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011714 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011715 }
Mike Stump11289f42009-09-09 15:08:12 +000011716
Ted Kremenek73295fa2008-07-23 18:04:17 +000011717 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011718 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011719 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11720 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011721 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011722 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011723 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11724 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011725 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011726 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011727 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011728 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011729 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011730 EnclosingContext = IMPDecl->getClassInterface();
11731 assert(EnclosingContext && "Implementation has no class interface!");
11732 }
11733 else
11734 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011735 } else {
11736 if (ObjCCategoryDecl *CDecl =
11737 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011738 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011739 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011740 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011741 }
11742 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011743 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011744 }
Mike Stump11289f42009-09-09 15:08:12 +000011745
Ted Kremenek73295fa2008-07-23 18:04:17 +000011746 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011747 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11748 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011749 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011750
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011751 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011752 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011753 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011754 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011755 && !isa<TagDecl>(PrevDecl)) {
11756 Diag(Loc, diag::err_duplicate_member) << II;
11757 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11758 NewID->setInvalidDecl();
11759 }
11760 }
11761
Ted Kremenek73295fa2008-07-23 18:04:17 +000011762 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011763 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011764
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011765 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011766 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011767
John McCall31168b02011-06-15 23:02:42 +000011768 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011769 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011770 NewID->setInvalidDecl();
11771
Douglas Gregor3baa6702011-09-12 16:11:24 +000011772 if (D.getDeclSpec().isModulePrivateSpecified())
11773 NewID->setModulePrivate();
11774
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011775 if (II) {
11776 // FIXME: When interfaces are DeclContexts, we'll need to add
11777 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011778 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011779 IdResolver.AddDecl(NewID);
11780 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011781
John McCall5fb5df92012-06-20 06:18:46 +000011782 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011783 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011784 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011785
John McCall48871652010-08-21 09:40:31 +000011786 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011787}
11788
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011789/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011790/// class and class extensions. For every class \@interface and class
11791/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011792/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011793void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011794 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011795 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011796 return;
11797
11798 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11799 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11800
Richard Smithcaf33902011-10-10 18:28:20 +000011801 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011802 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011803 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011804 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011805 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011806 if (!CD->IsClassExtension())
11807 return;
11808 }
11809 // No need to add this to end of @implementation.
11810 else
11811 return;
11812 }
11813 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011814 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11815 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011816
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011817 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011818 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011819 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011820 Context.getTrivialTypeSourceInfo(Context.CharTy,
11821 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011822 ObjCIvarDecl::Private, BW,
11823 true);
11824 AllIvarDecls.push_back(Ivar);
11825}
11826
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011827void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11828 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11829 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000011830 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000011831
Eric Christopher7457aaf2012-07-19 22:22:51 +000011832 // If this is an Objective-C @implementation or category and we have
11833 // new fields here we should reset the layout of the interface since
11834 // it will now change.
11835 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11836 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11837 switch (DC->getKind()) {
11838 default: break;
11839 case Decl::ObjCCategory:
11840 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11841 break;
11842 case Decl::ObjCImplementation:
11843 Context.
11844 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11845 break;
11846 }
11847 }
11848
Eli Friedmana7679412012-02-07 05:00:47 +000011849 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11850
11851 // Start counting up the number of named members; make sure to include
11852 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000011853 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000011854 if (Record) {
11855 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11856 e = Record->decls_end(); i != e; i++) {
11857 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11858 if (IFD->getDeclName())
11859 ++NumNamedMembers;
11860 }
11861 }
11862
11863 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011864 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000011865
John McCall31168b02011-06-15 23:02:42 +000011866 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011867 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000011868 i != end; ++i) {
11869 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000011870
Chris Lattner720a0542007-01-25 00:44:24 +000011871 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000011872 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000011873
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011874 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000011875 // Remember all fields written by the user.
11876 RecFields.push_back(FD);
11877 }
Mike Stump11289f42009-09-09 15:08:12 +000011878
Chris Lattner73bf7b42009-03-05 22:45:59 +000011879 // If the field is already invalid for some reason, don't emit more
11880 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011881 if (FD->isInvalidDecl()) {
11882 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000011883 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000011884 }
Mike Stump11289f42009-09-09 15:08:12 +000011885
Douglas Gregorac1fb652009-03-24 19:52:54 +000011886 // C99 6.7.2.1p2:
11887 // A structure or union shall not contain a member with
11888 // incomplete or function type (hence, a structure shall not
11889 // contain an instance of itself, but may contain a pointer to
11890 // an instance of itself), except that the last member of a
11891 // structure with more than one named member may have incomplete
11892 // array type; such a structure (and any union containing,
11893 // possibly recursively, a member that is such a structure)
11894 // shall not be a member of a structure or an element of an
11895 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000011896 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011897 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000011898 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011899 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000011900 FD->setInvalidDecl();
11901 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000011902 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000011903 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000011904 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000011905 ((getLangOpts().MicrosoftExt ||
11906 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000011907 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011908 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000011909 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000011910 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000011911 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000011912 unsigned DiagID = 0;
11913 if (Record->isUnion())
11914 DiagID = getLangOpts().MicrosoftExt
11915 ? diag::ext_flexible_array_union_ms
11916 : getLangOpts().CPlusPlus
11917 ? diag::ext_flexible_array_union_gnu
11918 : diag::err_flexible_array_union;
11919 else if (Fields.size() == 1)
11920 DiagID = getLangOpts().MicrosoftExt
11921 ? diag::ext_flexible_array_empty_aggregate_ms
11922 : getLangOpts().CPlusPlus
11923 ? diag::ext_flexible_array_empty_aggregate_gnu
11924 : NumNamedMembers < 1
11925 ? diag::err_flexible_array_empty_aggregate
11926 : 0;
11927
11928 if (DiagID)
11929 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11930 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000011931 // While the layout of types that contain virtual bases is not specified
11932 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11933 // virtual bases after the derived members. This would make a flexible
11934 // array member declared at the end of an object not adjacent to the end
11935 // of the type.
11936 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11937 if (RD->getNumVBases() != 0)
11938 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11939 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000011940 if (!getLangOpts().C99)
11941 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11942 << FD->getDeclName() << Record->getTagKind();
11943
Richard Smith6fa28ff2014-01-11 00:53:35 +000011944 // If the element type has a non-trivial destructor, we would not
11945 // implicitly destroy the elements, so disallow it for now.
11946 //
11947 // FIXME: GCC allows this. We should probably either implicitly delete
11948 // the destructor of the containing class, or just allow this.
11949 QualType BaseElem = Context.getBaseElementType(FD->getType());
11950 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
11951 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000011952 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011953 FD->setInvalidDecl();
11954 EnclosingDecl->setInvalidDecl();
11955 continue;
11956 }
Chris Lattner720a0542007-01-25 00:44:24 +000011957 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000011958 if (Record)
11959 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000011960 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000011961 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000011962 diag::err_field_incomplete)) {
11963 // Incomplete type
11964 FD->setInvalidDecl();
11965 EnclosingDecl->setInvalidDecl();
11966 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011967 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000011968 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11969 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011970 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000011971 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000011972 } else {
11973 // If this is a struct/class and this is not the last element, reject
11974 // it. Note that GCC supports variable sized arrays in the middle of
11975 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000011976 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000011977 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000011978 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000011979 else {
11980 // We support flexible arrays at the end of structs in
11981 // other structs as an extension.
11982 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11983 << FD->getDeclName();
11984 if (Record)
11985 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000011986 }
Chris Lattner720a0542007-01-25 00:44:24 +000011987 }
11988 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000011989 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11990 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11991 diag::err_abstract_type_in_decl,
11992 AbstractIvarType)) {
11993 // Ivars can not have abstract class types
11994 FD->setInvalidDecl();
11995 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000011996 if (Record && FDTTy->getDecl()->hasObjectMember())
11997 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000011998 if (Record && FDTTy->getDecl()->hasVolatileMember())
11999 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012000 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012001 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012002 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12003 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12004 QualType T = Context.getObjCObjectPointerType(FD->getType());
12005 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012006 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12007 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12008 // It's an error in ARC if a field has lifetime.
12009 // We don't want to report this in a system header, though,
12010 // so we just make the field unavailable.
12011 // FIXME: that's really not sufficient; we need to make the type
12012 // itself invalid to, say, initialize or copy.
12013 QualType T = FD->getType();
12014 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12015 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12016 SourceLocation loc = FD->getLocation();
12017 if (getSourceManager().isInSystemHeader(loc)) {
12018 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012019 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12020 "this system field has retaining ownership",
12021 loc));
John McCall31168b02011-06-15 23:02:42 +000012022 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012023 } else {
12024 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012025 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012026 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012027 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012028 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012029 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012030 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012031 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012032 if (FD->getType()->isObjCObjectPointerType() ||
12033 FD->getType().isObjCGCStrong())
12034 Record->setHasObjectMember(true);
12035 else if (Context.getAsArrayType(FD->getType())) {
12036 QualType BaseType = Context.getBaseElementType(FD->getType());
12037 if (BaseType->isRecordType() &&
12038 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012039 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012040 else if (BaseType->isObjCObjectPointerType() ||
12041 BaseType.isObjCGCStrong())
12042 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012043 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012044 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012045 if (Record && FD->getType().isVolatileQualified())
12046 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012047 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012048 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012049 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012050 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012051
Chris Lattner82625602007-01-24 02:26:21 +000012052 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012053 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012054 bool Completed = false;
12055 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12056 if (!CXXRecord->isInvalidDecl()) {
12057 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012058 for (CXXRecordDecl::conversion_iterator
12059 I = CXXRecord->conversion_begin(),
12060 E = CXXRecord->conversion_end(); I != E; ++I)
12061 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012062
12063 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012064 if (CXXRecord->hasUserDeclaredDestructor()) {
12065 // Adjust user-defined destructor exception spec.
12066 if (getLangOpts().CPlusPlus11)
12067 AdjustDestructorExceptionSpec(CXXRecord,
12068 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012069 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012070
Douglas Gregor8fb95122010-09-29 00:15:42 +000012071 // Add any implicitly-declared members to this class.
12072 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12073
12074 // If we have virtual base classes, we may end up finding multiple
12075 // final overriders for a given virtual function. Check for this
12076 // problem now.
12077 if (CXXRecord->getNumVBases()) {
12078 CXXFinalOverriderMap FinalOverriders;
12079 CXXRecord->getFinalOverriders(FinalOverriders);
12080
12081 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12082 MEnd = FinalOverriders.end();
12083 M != MEnd; ++M) {
12084 for (OverridingMethods::iterator SO = M->second.begin(),
12085 SOEnd = M->second.end();
12086 SO != SOEnd; ++SO) {
12087 assert(SO->second.size() > 0 &&
12088 "Virtual function without overridding functions?");
12089 if (SO->second.size() == 1)
12090 continue;
12091
12092 // C++ [class.virtual]p2:
12093 // In a derived class, if a virtual member function of a base
12094 // class subobject has more than one final overrider the
12095 // program is ill-formed.
12096 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012097 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012098 Diag(M->first->getLocation(),
12099 diag::note_overridden_virtual_function);
12100 for (OverridingMethods::overriding_iterator
12101 OM = SO->second.begin(),
12102 OMEnd = SO->second.end();
12103 OM != OMEnd; ++OM)
12104 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012105 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012106
12107 Record->setInvalidDecl();
12108 }
12109 }
12110 CXXRecord->completeDefinition(&FinalOverriders);
12111 Completed = true;
12112 }
12113 }
12114 }
12115 }
12116
12117 if (!Completed)
12118 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012119
Richard Smith848e1f12013-02-01 08:12:08 +000012120 if (Record->hasAttrs())
12121 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012122
Serge Pavlov3cb80222013-11-14 02:13:03 +000012123 // Check if the structure/union declaration is a type that can have zero
12124 // size in C. For C this is a language extension, for C++ it may cause
12125 // compatibility problems.
12126 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012127 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012128 CheckForZeroSize = true;
12129 } else {
12130 // For C++ filter out types that cannot be referenced in C code.
12131 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12132 CheckForZeroSize =
12133 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12134 !CXXRecord->isDependentType() &&
12135 CXXRecord->isCLike();
12136 }
12137 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012138 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012139 bool IsEmpty = true;
12140 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012141 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012142 E = Record->field_end();
12143 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12144 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012145 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012146 if (I->getBitWidthValue(Context) > 0)
12147 ZeroSize = false;
12148 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012149 ++NonBitFields;
12150 QualType FieldType = I->getType();
12151 if (FieldType->isIncompleteType() ||
12152 !Context.getTypeSizeInChars(FieldType).isZero())
12153 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012154 }
12155 }
12156
Serge Pavlov3cb80222013-11-14 02:13:03 +000012157 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12158 // allowed in C++, but warn if its declaration is inside
12159 // extern "C" block.
12160 if (ZeroSize) {
12161 Diag(RecLoc, getLangOpts().CPlusPlus ?
12162 diag::warn_zero_size_struct_union_in_extern_c :
12163 diag::warn_zero_size_struct_union_compat)
12164 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12165 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012166
Serge Pavlov3cb80222013-11-14 02:13:03 +000012167 // Structs without named members are extension in C (C99 6.7.2.1p7),
12168 // but are accepted by GCC.
12169 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12170 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12171 diag::ext_no_named_members_in_struct_union)
12172 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012173 }
12174 }
Chris Lattner622c1932008-02-06 00:51:33 +000012175 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012176 ObjCIvarDecl **ClsFields =
12177 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012178 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012179 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012180 // Add ivar's to class's DeclContext.
12181 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12182 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012183 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012184 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012185 // Must enforce the rule that ivars in the base classes may not be
12186 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012187 if (ID->getSuperClass())
12188 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012189 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012190 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012191 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012192 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12193 // Ivar declared in @implementation never belongs to the implementation.
12194 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012195 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012196 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012197 IMPDecl->setIvarLBraceLoc(LBrac);
12198 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012199 } else if (ObjCCategoryDecl *CDecl =
12200 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012201 // case of ivars in class extension; all other cases have been
12202 // reported as errors elsewhere.
12203 // FIXME. Class extension does not have a LocEnd field.
12204 // CDecl->setLocEnd(RBrac);
12205 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012206 // Diagnose redeclaration of private ivars.
12207 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012208 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012209 if (IDecl) {
12210 if (const ObjCIvarDecl *ClsIvar =
12211 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12212 Diag(ClsFields[i]->getLocation(),
12213 diag::err_duplicate_ivar_declaration);
12214 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12215 continue;
12216 }
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012217 for (ObjCInterfaceDecl::known_extensions_iterator
12218 Ext = IDecl->known_extensions_begin(),
12219 ExtEnd = IDecl->known_extensions_end();
12220 Ext != ExtEnd; ++Ext) {
12221 if (const ObjCIvarDecl *ClsExtIvar
12222 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012223 Diag(ClsFields[i]->getLocation(),
12224 diag::err_duplicate_ivar_declaration);
12225 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12226 continue;
12227 }
12228 }
12229 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012230 ClsFields[i]->setLexicalDeclContext(CDecl);
12231 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012232 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012233 CDecl->setIvarLBraceLoc(LBrac);
12234 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012235 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012236 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012237
12238 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012239 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012240}
12241
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012242/// \brief Determine whether the given integral value is representable within
12243/// the given type T.
12244static bool isRepresentableIntegerValue(ASTContext &Context,
12245 llvm::APSInt &Value,
12246 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012247 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012248 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012249
Douglas Gregor0bf31402010-10-08 23:50:27 +000012250 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012251 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012252 --BitWidth;
12253 return Value.getActiveBits() <= BitWidth;
12254 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012255 return Value.getMinSignedBits() <= BitWidth;
12256}
12257
12258// \brief Given an integral type, return the next larger integral type
12259// (or a NULL type of no such type exists).
12260static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12261 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12262 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012263 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012264 const unsigned NumTypes = 4;
12265 QualType SignedIntegralTypes[NumTypes] = {
12266 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12267 };
12268 QualType UnsignedIntegralTypes[NumTypes] = {
12269 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12270 Context.UnsignedLongLongTy
12271 };
12272
12273 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012274 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12275 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012276 for (unsigned I = 0; I != NumTypes; ++I)
12277 if (Context.getTypeSize(Types[I]) > BitWidth)
12278 return Types[I];
12279
12280 return QualType();
12281}
12282
Douglas Gregor954f6b272009-03-17 19:05:46 +000012283EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12284 EnumConstantDecl *LastEnumConst,
12285 SourceLocation IdLoc,
12286 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012287 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012288 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012289 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012290 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012291
12292 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12293 Val = 0;
12294
Eli Friedman7c6515a2011-12-06 00:10:34 +000012295 if (Val)
12296 Val = DefaultLvalueConversion(Val).take();
12297
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012298 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012299 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012300 EltTy = Context.DependentTy;
12301 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012302 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012303 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000012304 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000012305 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12306 // constant-expression in the enumerator-definition shall be a converted
12307 // constant expression of the underlying type.
12308 EltTy = Enum->getIntegerType();
12309 ExprResult Converted =
12310 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12311 CCEK_Enumerator);
12312 if (Converted.isInvalid())
12313 Val = 0;
12314 else
12315 Val = Converted.take();
12316 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012317 !(Val = VerifyIntegerConstantExpression(Val,
12318 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012319 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012320 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012321 if (Enum->isFixed()) {
12322 EltTy = Enum->getIntegerType();
12323
Richard Smithf8379a02012-01-18 23:55:52 +000012324 // In Obj-C and Microsoft mode, require the enumeration value to be
12325 // representable in the underlying type of the enumeration. In C++11,
12326 // we perform a non-narrowing conversion as part of converted constant
12327 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012328 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000012329 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000012330 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012331 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012332 } else
12333 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012334 } else
John Wiegley01296292011-04-08 18:41:53 +000012335 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012336 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012337 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012338 // If the underlying type is not fixed, the type of each enumerator
12339 // is the type of its initializing value:
12340 // - If an initializer is specified for an enumerator, the
12341 // initializing value has the same type as the expression.
12342 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012343 } else {
12344 // C99 6.7.2.2p2:
12345 // The expression that defines the value of an enumeration constant
12346 // shall be an integer constant expression that has a value
12347 // representable as an int.
12348
12349 // Complain if the value is not representable in an int.
12350 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12351 Diag(IdLoc, diag::ext_enum_value_not_int)
12352 << EnumVal.toString(10) << Val->getSourceRange()
12353 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12354 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12355 // Force the type of the expression to 'int'.
12356 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12357 }
12358 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012359 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012360 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012361 }
12362 }
Mike Stump11289f42009-09-09 15:08:12 +000012363
Douglas Gregor954f6b272009-03-17 19:05:46 +000012364 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012365 if (Enum->isDependentType())
12366 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012367 else if (!LastEnumConst) {
12368 // C++0x [dcl.enum]p5:
12369 // If the underlying type is not fixed, the type of each enumerator
12370 // is the type of its initializing value:
12371 // - If no initializer is specified for the first enumerator, the
12372 // initializing value has an unspecified integral type.
12373 //
12374 // GCC uses 'int' for its unspecified integral type, as does
12375 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012376 if (Enum->isFixed()) {
12377 EltTy = Enum->getIntegerType();
12378 }
12379 else {
12380 EltTy = Context.IntTy;
12381 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012382 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012383 // Assign the last value + 1.
12384 EnumVal = LastEnumConst->getInitVal();
12385 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012386 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012387
12388 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012389 if (EnumVal < LastEnumConst->getInitVal()) {
12390 // C++0x [dcl.enum]p5:
12391 // If the underlying type is not fixed, the type of each enumerator
12392 // is the type of its initializing value:
12393 //
12394 // - Otherwise the type of the initializing value is the same as
12395 // the type of the initializing value of the preceding enumerator
12396 // unless the incremented value is not representable in that type,
12397 // in which case the type is an unspecified integral type
12398 // sufficient to contain the incremented value. If no such type
12399 // exists, the program is ill-formed.
12400 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012401 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012402 // There is no integral type larger enough to represent this
12403 // value. Complain, then allow the value to wrap around.
12404 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012405 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012406 ++EnumVal;
12407 if (Enum->isFixed())
12408 // When the underlying type is fixed, this is ill-formed.
12409 Diag(IdLoc, diag::err_enumerator_wrapped)
12410 << EnumVal.toString(10)
12411 << EltTy;
12412 else
12413 Diag(IdLoc, diag::warn_enumerator_too_large)
12414 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012415 } else {
12416 EltTy = T;
12417 }
12418
12419 // Retrieve the last enumerator's value, extent that type to the
12420 // type that is supposed to be large enough to represent the incremented
12421 // value, then increment.
12422 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012423 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012424 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012425 ++EnumVal;
12426
12427 // If we're not in C++, diagnose the overflow of enumerator values,
12428 // which in C99 means that the enumerator value is not representable in
12429 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12430 // permits enumerator values that are representable in some larger
12431 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012432 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012433 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012434 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012435 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12436 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12437 Diag(IdLoc, diag::ext_enum_value_not_int)
12438 << EnumVal.toString(10) << 1;
12439 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012440 }
12441 }
Mike Stump11289f42009-09-09 15:08:12 +000012442
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012443 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012444 // Make the enumerator value match the signedness and size of the
12445 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012446 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012447 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012448 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012449
Douglas Gregor954f6b272009-03-17 19:05:46 +000012450 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012451 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012452}
12453
12454
John McCall811a0f52010-10-22 23:36:17 +000012455Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12456 SourceLocation IdLoc, IdentifierInfo *Id,
12457 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012458 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012459 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012460 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012461 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012462
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012463 // The scope passed in may not be a decl scope. Zip up the scope tree until
12464 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012465 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012466
Chris Lattner8116d1b2007-01-25 22:38:29 +000012467 // Verify that there isn't already something declared with this name in this
12468 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012469 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012470 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012471 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012472 // Maybe we will complain about the shadowed template parameter.
12473 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12474 // Just pretend that we didn't see the previous declaration.
12475 PrevDecl = 0;
12476 }
12477
12478 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012479 // When in C++, we may get a TagDecl with the same name; in this case the
12480 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012481 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012482 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012483 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012484 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012485 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012486 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012487 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012488 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012489 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012490 }
12491 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012492
Aaron Ballman24a10472012-07-19 03:12:23 +000012493 // C++ [class.mem]p15:
12494 // If T is the name of a class, then each of the following shall have a name
12495 // different from T:
12496 // - every enumerator of every member of class T that is an unscoped
12497 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012498 if (CXXRecordDecl *Record
12499 = dyn_cast<CXXRecordDecl>(
12500 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012501 if (!TheEnumDecl->isScoped() &&
12502 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012503 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12504
John McCall811a0f52010-10-22 23:36:17 +000012505 EnumConstantDecl *New =
12506 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012507
John McCall553c0792010-01-23 00:46:32 +000012508 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012509 // Process attributes.
12510 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12511
12512 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012513 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012514 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012515 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012516
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012517 ActOnDocumentableDecl(New);
12518
John McCall48871652010-08-21 09:40:31 +000012519 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012520}
12521
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012522// Returns true when the enum initial expression does not trigger the
12523// duplicate enum warning. A few common cases are exempted as follows:
12524// Element2 = Element1
12525// Element2 = Element1 + 1
12526// Element2 = Element1 - 1
12527// Where Element2 and Element1 are from the same enum.
12528static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12529 Expr *InitExpr = ECD->getInitExpr();
12530 if (!InitExpr)
12531 return true;
12532 InitExpr = InitExpr->IgnoreImpCasts();
12533
12534 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12535 if (!BO->isAdditiveOp())
12536 return true;
12537 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12538 if (!IL)
12539 return true;
12540 if (IL->getValue() != 1)
12541 return true;
12542
12543 InitExpr = BO->getLHS();
12544 }
12545
12546 // This checks if the elements are from the same enum.
12547 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12548 if (!DRE)
12549 return true;
12550
12551 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12552 if (!EnumConstant)
12553 return true;
12554
12555 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12556 Enum)
12557 return true;
12558
12559 return false;
12560}
12561
12562struct DupKey {
12563 int64_t val;
12564 bool isTombstoneOrEmptyKey;
12565 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12566 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12567};
12568
12569static DupKey GetDupKey(const llvm::APSInt& Val) {
12570 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12571 false);
12572}
12573
12574struct DenseMapInfoDupKey {
12575 static DupKey getEmptyKey() { return DupKey(0, true); }
12576 static DupKey getTombstoneKey() { return DupKey(1, true); }
12577 static unsigned getHashValue(const DupKey Key) {
12578 return (unsigned)(Key.val * 37);
12579 }
12580 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12581 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12582 LHS.val == RHS.val;
12583 }
12584};
12585
12586// Emits a warning when an element is implicitly set a value that
12587// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012588static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12589 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012590 QualType EnumType) {
12591 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12592 Enum->getLocation()) ==
12593 DiagnosticsEngine::Ignored)
12594 return;
12595 // Avoid anonymous enums
12596 if (!Enum->getIdentifier())
12597 return;
12598
12599 // Only check for small enums.
12600 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12601 return;
12602
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012603 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12604 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012605
12606 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12607 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12608 ValueToVectorMap;
12609
12610 DuplicatesVector DupVector;
12611 ValueToVectorMap EnumMap;
12612
12613 // Populate the EnumMap with all values represented by enum constants without
12614 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012615 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012616 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012617
12618 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12619 // this constant. Skip this enum since it may be ill-formed.
12620 if (!ECD) {
12621 return;
12622 }
12623
12624 if (ECD->getInitExpr())
12625 continue;
12626
12627 DupKey Key = GetDupKey(ECD->getInitVal());
12628 DeclOrVector &Entry = EnumMap[Key];
12629
12630 // First time encountering this value.
12631 if (Entry.isNull())
12632 Entry = ECD;
12633 }
12634
12635 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012636 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012637 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12638 if (!ValidDuplicateEnum(ECD, Enum))
12639 continue;
12640
12641 DupKey Key = GetDupKey(ECD->getInitVal());
12642
12643 DeclOrVector& Entry = EnumMap[Key];
12644 if (Entry.isNull())
12645 continue;
12646
12647 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12648 // Ensure constants are different.
12649 if (D == ECD)
12650 continue;
12651
12652 // Create new vector and push values onto it.
12653 ECDVector *Vec = new ECDVector();
12654 Vec->push_back(D);
12655 Vec->push_back(ECD);
12656
12657 // Update entry to point to the duplicates vector.
12658 Entry = Vec;
12659
12660 // Store the vector somewhere we can consult later for quick emission of
12661 // diagnostics.
12662 DupVector.push_back(Vec);
12663 continue;
12664 }
12665
12666 ECDVector *Vec = Entry.get<ECDVector*>();
12667 // Make sure constants are not added more than once.
12668 if (*Vec->begin() == ECD)
12669 continue;
12670
12671 Vec->push_back(ECD);
12672 }
12673
12674 // Emit diagnostics.
12675 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12676 DupVectorEnd = DupVector.end();
12677 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12678 ECDVector *Vec = *DupVectorIter;
12679 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12680
12681 // Emit warning for one enum constant.
12682 ECDVector::iterator I = Vec->begin();
12683 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12684 << (*I)->getName() << (*I)->getInitVal().toString(10)
12685 << (*I)->getSourceRange();
12686 ++I;
12687
12688 // Emit one note for each of the remaining enum constants with
12689 // the same value.
12690 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12691 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12692 << (*I)->getName() << (*I)->getInitVal().toString(10)
12693 << (*I)->getSourceRange();
12694 delete Vec;
12695 }
12696}
12697
Mike Stump6814d1c2009-05-16 07:06:02 +000012698void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012699 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012700 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012701 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012702 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012703 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012704
12705 if (Attr)
12706 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012707
Eli Friedmand0e60972009-12-11 01:34:50 +000012708 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012709 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012710 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012711 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012712 if (!ECD) continue;
12713
12714 ECD->setType(EnumType);
12715 }
12716
John McCall9aa35be2010-05-06 08:49:23 +000012717 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012718 return;
12719 }
12720
Chris Lattner67933c02007-08-28 05:10:31 +000012721 // TODO: If the result value doesn't fit in an int, it must be a long or long
12722 // long value. ISO C does not support this, but GCC does as an extension,
12723 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012724 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12725 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12726 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012727
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012728 // Verify that all the values are okay, compute the size of the values, and
12729 // reverse the list.
12730 unsigned NumNegativeBits = 0;
12731 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012732
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012733 // Keep track of whether all elements have type int.
12734 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012735
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012736 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012737 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012738 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012739 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012740
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012741 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012742
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012743 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012744 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012745 NumPositiveBits = std::max(NumPositiveBits,
12746 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012747 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012748 NumNegativeBits = std::max(NumNegativeBits,
12749 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012750
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012751 // Keep track of whether every enum element has type int (very commmon).
12752 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012753 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012754 }
Mike Stump11289f42009-09-09 15:08:12 +000012755
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012756 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012757 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012758 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012759
John McCall56774992009-12-09 09:09:27 +000012760 // C++0x N3000 [conv.prom]p3:
12761 // An rvalue of an unscoped enumeration type whose underlying
12762 // type is not fixed can be converted to an rvalue of the first
12763 // of the following types that can represent all the values of
12764 // the enumeration: int, unsigned int, long int, unsigned long
12765 // int, long long int, or unsigned long long int.
12766 // C99 6.4.4.3p2:
12767 // An identifier declared as an enumeration constant has type int.
12768 // The C99 rule is modified by a gcc extension
12769 QualType BestPromotionType;
12770
Aaron Ballman9ead1242013-12-19 02:39:40 +000012771 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012772 // -fshort-enums is the equivalent to specifying the packed attribute on all
12773 // enum definitions.
12774 if (LangOpts.ShortEnums)
12775 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012776
Douglas Gregor0bf31402010-10-08 23:50:27 +000012777 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012778 BestType = Enum->getIntegerType();
12779 if (BestType->isPromotableIntegerType())
12780 BestPromotionType = Context.getPromotedIntegerType(BestType);
12781 else
12782 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012783 // We don't need to set BestWidth, because BestType is going to be the type
12784 // of the enumerators, but we do anyway because otherwise some compilers
12785 // warn that it might be used uninitialized.
12786 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012787 }
12788 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012789 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012790 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012791 // If it's packed, check also if it fits a char or a short.
12792 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012793 BestType = Context.SignedCharTy;
12794 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012795 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012796 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012797 BestType = Context.ShortTy;
12798 BestWidth = ShortWidth;
12799 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012800 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012801 BestWidth = IntWidth;
12802 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012803 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012804
John McCall56774992009-12-09 09:09:27 +000012805 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012806 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012807 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012808 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012809
Chris Lattner3a370bf2007-08-29 17:31:48 +000012810 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012811 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12812 BestType = Context.LongLongTy;
12813 }
12814 }
John McCall56774992009-12-09 09:09:27 +000012815 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012816 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012817 // If there is no negative value, figure out the smallest type that fits
12818 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012819 // If it's packed, check also if it fits a char or a short.
12820 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012821 BestType = Context.UnsignedCharTy;
12822 BestPromotionType = Context.IntTy;
12823 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012824 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012825 BestType = Context.UnsignedShortTy;
12826 BestPromotionType = Context.IntTy;
12827 BestWidth = ShortWidth;
12828 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012829 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012830 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000012831 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012832 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012833 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012834 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000012835 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012836 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012837 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012838 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012839 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000012840 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012841 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012842 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012843 "How could an initializer get larger than ULL?");
12844 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012845 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012846 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012847 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012848 }
12849 }
Mike Stump11289f42009-09-09 15:08:12 +000012850
Chris Lattner3a370bf2007-08-29 17:31:48 +000012851 // Loop over all of the enumerator constants, changing their types to match
12852 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012853 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000012854 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012855 if (!ECD) continue; // Already issued a diagnostic.
12856
12857 // Standard C says the enumerators have int type, but we allow, as an
12858 // extension, the enumerators to be larger than int size. If each
12859 // enumerator value fits in an int, type it as an int, otherwise type it the
12860 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12861 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000012862
12863 // Determine whether the value fits into an int.
12864 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012865
12866 // If it fits into an integer type, force it. Otherwise force it to match
12867 // the enum decl type.
12868 QualType NewTy;
12869 unsigned NewWidth;
12870 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000012871 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000012872 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012873 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000012874 NewTy = Context.IntTy;
12875 NewWidth = IntWidth;
12876 NewSign = true;
12877 } else if (ECD->getType() == BestType) {
12878 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000012879 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012880 // C++ [dcl.enum]p4: Following the closing brace of an
12881 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012882 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012883 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012884 continue;
12885 } else {
12886 NewTy = BestType;
12887 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012888 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012889 }
12890
12891 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000012892 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012893 InitVal.setIsSigned(NewSign);
12894 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000012895
Chris Lattner3a370bf2007-08-29 17:31:48 +000012896 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000012897 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000012898 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000012899 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000012900 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000012901 ECD->getInitExpr(),
12902 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000012903 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000012904 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012905 // C++ [dcl.enum]p4: Following the closing brace of an
12906 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012907 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012908 ECD->setType(EnumType);
12909 else
12910 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012911 }
Mike Stump11289f42009-09-09 15:08:12 +000012912
John McCall9aa35be2010-05-06 08:49:23 +000012913 Enum->completeDefinition(BestType, BestPromotionType,
12914 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000012915
12916 // If we're declaring a function, ensure this decl isn't forgotten about -
12917 // it needs to go into the function scope.
12918 if (InFunctionDeclarator)
12919 DeclsInPrototypeScope.push_back(Enum);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012920
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012921 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000012922
12923 // Now that the enum type is defined, ensure it's not been underaligned.
12924 if (Enum->hasAttrs())
12925 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012926}
Chris Lattner1300fb92007-01-23 23:42:53 +000012927
Abramo Bagnara348823a2011-03-03 14:20:18 +000012928Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12929 SourceLocation StartLoc,
12930 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000012931 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000012932
Douglas Gregor278f52e2009-05-30 00:08:05 +000012933 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000012934 AsmString, StartLoc,
12935 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012936 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000012937 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000012938}
Eli Friedman5ed51982009-06-05 02:44:36 +000012939
Douglas Gregor22d09742012-01-03 18:04:46 +000012940DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12941 SourceLocation ImportLoc,
12942 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000012943 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000012944 Module::AllVisible,
12945 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000012946 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000012947 return true;
12948
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012949 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000012950 Module *ModCheck = Mod;
12951 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12952 // If we've run out of module parents, just drop the remaining identifiers.
12953 // We need the length to be consistent.
12954 if (!ModCheck)
12955 break;
12956 ModCheck = ModCheck->Parent;
12957
12958 IdentifierLocs.push_back(Path[I].second);
12959 }
12960
12961 ImportDecl *Import = ImportDecl::Create(Context,
12962 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000012963 AtLoc.isValid()? AtLoc : ImportLoc,
12964 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000012965 Context.getTranslationUnitDecl()->addDecl(Import);
12966 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000012967}
12968
Richard Smithce587f52013-11-15 04:24:58 +000012969void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
12970 // FIXME: Should we synthesize an ImportDecl here?
12971 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
12972 /*Complain=*/true);
12973}
12974
Douglas Gregorc147b0b2013-01-12 01:29:50 +000012975void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12976 // Create the implicit import declaration.
12977 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12978 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12979 Loc, Mod, Loc);
12980 TU->addDecl(ImportD);
12981 Consumer.HandleImplicitImportDecl(ImportD);
12982
12983 // Make the module visible.
Douglas Gregorfb912652013-03-20 21:10:35 +000012984 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12985 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000012986}
12987
David Chisnall0867d9c2012-02-18 16:12:34 +000012988void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12989 IdentifierInfo* AliasName,
12990 SourceLocation PragmaLoc,
12991 SourceLocation NameLoc,
12992 SourceLocation AliasNameLoc) {
12993 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12994 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000012995 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
12996 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000012997
12998 if (PrevDecl)
12999 PrevDecl->addAttr(Attr);
13000 else
13001 (void)ExtnameUndeclaredIdentifiers.insert(
13002 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13003}
13004
Eli Friedman5ed51982009-06-05 02:44:36 +000013005void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13006 SourceLocation PragmaLoc,
13007 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013008 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013009
Eli Friedman5ed51982009-06-05 02:44:36 +000013010 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000013011 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013012 } else {
13013 (void)WeakUndeclaredIdentifiers.insert(
13014 std::pair<IdentifierInfo*,WeakInfo>
13015 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013016 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013017}
13018
13019void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13020 IdentifierInfo* AliasName,
13021 SourceLocation PragmaLoc,
13022 SourceLocation NameLoc,
13023 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013024 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13025 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013026 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013027
Eli Friedman5ed51982009-06-05 02:44:36 +000013028 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013029 if (!PrevDecl->hasAttr<AliasAttr>())
13030 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013031 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013032 } else {
13033 (void)WeakUndeclaredIdentifiers.insert(
13034 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013035 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013036}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013037
13038Decl *Sema::getObjCDeclContext() const {
13039 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13040}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013041
13042AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013043 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013044 // If we are within an Objective-C method, we should consult
13045 // both the availability of the method as well as the
13046 // enclosing class. If the class is (say) deprecated,
13047 // the entire method is considered deprecated from the
13048 // purpose of checking if the current context is deprecated.
13049 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13050 AvailabilityResult R = MD->getAvailability();
13051 if (R != AR_Available)
13052 return R;
13053 D = MD->getClassInterface();
13054 }
13055 // If we are within an Objective-c @implementation, it
13056 // gets the same availability context as the @interface.
13057 else if (const ObjCImplementationDecl *ID =
13058 dyn_cast<ObjCImplementationDecl>(D)) {
13059 D = ID->getClassInterface();
13060 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013061 return D->getAvailability();
13062}