blob: ec06285278905434e128a59455adb133232d9148 [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 Uhrain67b44c92014-02-13 20:14:07 +000065 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
66 bool AllowTemplates=false)
67 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
68 AllowClassTemplates(AllowTemplates) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000069 WantExpressionKeywords = false;
70 WantCXXNamedCasts = false;
71 WantRemainingKeywords = false;
72 }
73
Craig Toppere14c0f82014-03-12 04:55:44 +000074 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000075 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
76 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
77 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
78 return (IsType || AllowedTemplate) &&
79 (AllowInvalidDecl || !ND->isInvalidDecl());
80 }
81 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000082 }
83
84 private:
85 bool AllowInvalidDecl;
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000086 bool WantClassName;
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000087 bool AllowClassTemplates;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000088};
89
90}
91
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +000092/// \brief Determine whether the token kind starts a simple-type-specifier.
93bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
94 switch (Kind) {
95 // FIXME: Take into account the current language when deciding whether a
96 // token kind is a valid type specifier
97 case tok::kw_short:
98 case tok::kw_long:
99 case tok::kw___int64:
100 case tok::kw___int128:
101 case tok::kw_signed:
102 case tok::kw_unsigned:
103 case tok::kw_void:
104 case tok::kw_char:
105 case tok::kw_int:
106 case tok::kw_half:
107 case tok::kw_float:
108 case tok::kw_double:
109 case tok::kw_wchar_t:
110 case tok::kw_bool:
111 case tok::kw___underlying_type:
112 return true;
113
114 case tok::annot_typename:
115 case tok::kw_char16_t:
116 case tok::kw_char32_t:
117 case tok::kw_typeof:
David Majnemera5e92552013-09-22 01:24:26 +0000118 case tok::annot_decltype:
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +0000119 case tok::kw_decltype:
120 return getLangOpts().CPlusPlus;
121
122 default:
123 break;
124 }
125
126 return false;
127}
128
Douglas Gregorec6e1892009-02-04 19:16:12 +0000129/// \brief If the identifier refers to a type name within this scope,
130/// return the declaration of that type.
131///
132/// This routine performs ordinary name lookup of the identifier II
133/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000134/// determine whether the name refers to a type. If so, returns an
135/// opaque pointer (actually a QualType) corresponding to that
136/// type. Otherwise, returns NULL.
Dmitri Gribenko5267fdf2013-05-03 13:12:11 +0000137ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallba7bf592010-08-24 05:47:05 +0000138 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +0000139 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +0000140 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000141 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000142 bool WantNontrivialTypeSourceInfo,
143 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000144 // Determine where we will perform name lookup.
145 DeclContext *LookupCtx = 0;
146 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000147 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000148 if (ObjectType->isRecordType())
149 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000150 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000151 LookupCtx = computeDeclContext(*SS, false);
152
153 if (!LookupCtx) {
154 if (isDependentScopeSpecifier(*SS)) {
155 // C++ [temp.res]p3:
156 // A qualified-id that refers to a type and in which the
157 // nested-name-specifier depends on a template-parameter (14.6.2)
158 // shall be prefixed by the keyword typename to indicate that the
159 // qualified-id denotes a type, forming an
160 // elaborated-type-specifier (7.1.5.3).
161 //
162 // We therefore do not perform any name lookup if the result would
163 // refer to a member of an unknown specialization.
Richard Smith23d55872012-04-02 01:30:27 +0000164 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000165 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000166
John McCallc392f372010-06-11 00:33:02 +0000167 // We know from the grammar that this name refers to a type,
168 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +0000169 if (WantNontrivialTypeSourceInfo)
170 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
171
172 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallba7bf592010-08-24 05:47:05 +0000173 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000174 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000175 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000176
177 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000178 }
179
John McCallba7bf592010-08-24 05:47:05 +0000180 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000181 }
182
John McCall0b66eb32010-05-01 00:40:08 +0000183 if (!LookupCtx->isDependentContext() &&
184 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000185 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000186 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000187
188 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
189 // lookup for class-names.
190 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
191 LookupOrdinaryName;
192 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000193 if (LookupCtx) {
194 // Perform "qualified" name lookup into the declaration context we
195 // computed, which is either the type of the base of a member access
196 // expression or the declaration context associated with a prior
197 // nested-name-specifier.
198 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000199
Douglas Gregora25d65d2009-11-20 22:03:38 +0000200 if (ObjectTypePtr && Result.empty()) {
201 // C++ [basic.lookup.classref]p3:
202 // If the unqualified-id is ~type-name, the type-name is looked up
203 // in the context of the entire postfix-expression. If the type T of
204 // the object expression is of a class type C, the type-name is also
205 // looked up in the scope of class C. At least one of the lookups shall
206 // find a name that refers to (possibly cv-qualified) T.
207 LookupName(Result, S);
208 }
209 } else {
210 // Perform unqualified name lookup.
211 LookupName(Result, S);
212 }
213
Chris Lattnera3778332009-02-16 22:07:16 +0000214 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000215 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000216 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000217 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000218 if (CorrectedII) {
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +0000219 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000220 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000221 Kind, S, SS, Validator);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000222 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
223 TemplateTy Template;
224 bool MemberOfUnknownSpecialization;
225 UnqualifiedId TemplateName;
226 TemplateName.setIdentifier(NewII, NameLoc);
227 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
228 CXXScopeSpec NewSS, *NewSSPtr = SS;
229 if (SS && NNS) {
230 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
231 NewSSPtr = &NewSS;
232 }
233 if (Correction && (NNS || NewII != &II) &&
234 // Ignore a correction to a template type as the to-be-corrected
235 // identifier is not a template (typo correction for template names
236 // is handled elsewhere).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000237 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000238 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
239 false, Template, MemberOfUnknownSpecialization))) {
240 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
241 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000242 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000243 WantNontrivialTypeSourceInfo);
244 if (Ty) {
Richard Smithf9b15102013-08-17 00:46:16 +0000245 diagnoseTypo(Correction,
246 PDiag(diag::err_unknown_type_or_class_name_suggest)
247 << Result.getLookupName() << isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000248 if (SS && NNS)
249 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
250 *CorrectedII = NewII;
251 return Ty;
252 }
253 }
254 }
255 // If typo correction failed or was not performed, fall through
Chris Lattnera3778332009-02-16 22:07:16 +0000256 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000257 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000258 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000259 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000260
Chris Lattnere40853a2009-10-25 22:09:09 +0000261 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000262 // Recover from type-hiding ambiguities by hiding the type. We'll
263 // do the lookup again when looking for an object, and we can
264 // diagnose the error then. If we don't do this, then the error
265 // about hiding the type will be immediately followed by an error
266 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000267 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
268 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000269 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000270 }
John McCall6538c932009-10-10 05:48:19 +0000271
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000272 // Look to see if we have a type anywhere in the list of results.
273 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
274 Res != ResEnd; ++Res) {
275 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000276 if (!IIDecl ||
277 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000278 IIDecl->getLocation().getRawEncoding())
279 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000280 }
281 }
282
283 if (!IIDecl) {
284 // None of the entities we found is a type, so there is no way
285 // to even assume that the result is a type. In this case, don't
286 // complain about the ambiguity. The parser will either try to
287 // perform this lookup again (e.g., as an object name), which
288 // will produce the ambiguity, or will complain that it expected
289 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000290 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000291 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000292 }
293
294 // We found a type within the ambiguous lookup; diagnose the
295 // ambiguity and then return that type. This might be the right
296 // answer, or it might not be, but it suppresses any attempt to
297 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000298 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000299
Chris Lattnera3778332009-02-16 22:07:16 +0000300 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000301 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000302 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000303 }
304
Chris Lattner17e15f12009-10-25 17:16:46 +0000305 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000306
Chris Lattner17e15f12009-10-25 17:16:46 +0000307 QualType T;
308 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000309 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000310
Chris Lattner17e15f12009-10-25 17:16:46 +0000311 if (T.isNull())
312 T = Context.getTypeDeclType(TD);
Abramo Bagnara4244b432012-01-27 08:46:19 +0000313
314 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
315 // constructor or destructor name (in such a case, the scope specifier
316 // will be attached to the enclosing Expr or Decl node).
317 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor844cb502011-03-01 18:12:44 +0000318 if (WantNontrivialTypeSourceInfo) {
319 // Construct a type with type-source information.
320 TypeLocBuilder Builder;
321 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
322
323 T = getElaboratedType(ETK_None, *SS, T);
324 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000325 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor844cb502011-03-01 18:12:44 +0000326 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
327 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
328 } else {
329 T = getElaboratedType(ETK_None, *SS, T);
330 }
331 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000332 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000333 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000334 if (!HasTrailingDot)
335 T = Context.getObjCInterfaceType(IDecl);
336 }
337
338 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000339 // If it's not plausibly a type, suppress diagnostics.
340 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000341 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000342 }
John McCallba7bf592010-08-24 05:47:05 +0000343 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000344}
345
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000346/// isTagName() - This method is called *for error recovery purposes only*
347/// to determine if the specified name is a valid tag name ("struct foo"). If
348/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matosdc86f942012-08-31 18:45:21 +0000349/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
350/// cases in C where the user forgot to specify the tag.
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000351DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
352 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000353 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
354 LookupName(R, S, false);
355 R.suppressDiagnostics();
356 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000357 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000358 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000359 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matosdc86f942012-08-31 18:45:21 +0000360 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara6150c882010-05-11 21:36:43 +0000361 case TTK_Union: return DeclSpec::TST_union;
362 case TTK_Class: return DeclSpec::TST_class;
363 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000364 }
365 }
Mike Stump11289f42009-09-09 15:08:12 +0000366
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000367 return DeclSpec::TST_unspecified;
368}
369
Francois Pichet48c946e2011-04-13 02:38:49 +0000370/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
371/// if a CXXScopeSpec's type is equal to the type of one of the base classes
372/// then downgrade the missing typename error to a warning.
373/// This is needed for MSVC compatibility; Example:
374/// @code
375/// template<class T> class A {
376/// public:
377/// typedef int TYPE;
378/// };
379/// template<class T> class B : public A<T> {
380/// public:
381/// A<T>::TYPE a; // no typename required because A<T> is a base class.
382/// };
383/// @endcode
Francois Pichet9a57fb52011-10-11 01:50:09 +0000384bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000385 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000386 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000387
388 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
389 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
390 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
391 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
392 return true;
Francois Pichet9a57fb52011-10-11 01:50:09 +0000393 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000394 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000395 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000396}
397
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000398bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000399 SourceLocation IILoc,
400 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000401 CXXScopeSpec *SS,
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000402 ParsedType &SuggestedType,
403 bool AllowClassTemplates) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000404 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000405 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000406
Douglas Gregor2d435302009-12-30 17:04:44 +0000407 // There may have been a typo in the name of the type. Look up typo
408 // results, in case we have something that we can suggest.
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000409 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000410 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000411 LookupOrdinaryName, S, SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000412 Validator)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000413 if (Corrected.isKeyword()) {
414 // We corrected to a keyword.
Richard Smithf9b15102013-08-17 00:46:16 +0000415 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
416 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000417 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000418 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000419 if (!SS || !SS->isSet()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000420 diagnoseTypo(Corrected,
421 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000422 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000423 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
424 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000425 II->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000426 diagnoseTypo(Corrected,
427 PDiag(diag::err_unknown_nested_typename_suggest)
428 << II << DC << DroppedSpecifier << SS->getRange());
429 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000430 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000431 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000432
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000433 CXXScopeSpec tmpSS;
434 if (Corrected.getCorrectionSpecifier())
435 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
436 SourceRange(IILoc));
Richard Smithf9b15102013-08-17 00:46:16 +0000437 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000438 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
439 false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000440 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000441 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000442 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000443 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000444 }
445
David Blaikiebbafb8a2012-03-11 07:00:24 +0000446 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000447 // See if II is a class template that the user forgot to pass arguments to.
448 UnqualifiedId Name;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000449 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000450 CXXScopeSpec EmptySS;
451 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000452 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000453 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000454 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000455 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +0000456 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000457 Diag(IILoc, diag::err_template_missing_args) << TplName;
458 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
459 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
460 << TplDecl->getTemplateParameters()->getSourceRange();
461 }
462 return true;
463 }
464 }
465
Douglas Gregor15e56022009-10-13 23:27:22 +0000466 // FIXME: Should we move the logic that tries to recover from a missing tag
467 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
468
Douglas Gregor2d435302009-12-30 17:04:44 +0000469 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000470 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000471 else if (DeclContext *DC = computeDeclContext(*SS, false))
472 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000473 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000474 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000475 unsigned DiagID = diag::err_typename_missing;
Alp Tokerbfa39342014-01-14 12:51:41 +0000476 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000477 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000478
479 Diag(SS->getRange().getBegin(), DiagID)
Aaron Ballman691e2272014-01-03 14:48:20 +0000480 << SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000481 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000482 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000483 SuggestedType = ActOnTypenameType(S, SourceLocation(),
484 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000485 } else {
486 assert(SS && SS->isInvalid() &&
487 "Invalid scope specifier has already been diagnosed");
488 }
489
490 return true;
491}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000492
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000493/// \brief Determine whether the given result set contains either a type name
494/// or
495static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000496 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000497 NextToken.is(tok::less);
498
499 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
500 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
501 return true;
502
503 if (CheckTemplate && isa<TemplateDecl>(*I))
504 return true;
505 }
506
507 return false;
508}
509
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000510static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
511 Scope *S, CXXScopeSpec &SS,
512 IdentifierInfo *&Name,
513 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000514 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
515 SemaRef.LookupParsedName(R, S, &SS);
516 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000517 const char *TagName = 0;
518 const char *FixItTagName = 0;
519 switch (Tag->getTagKind()) {
520 case TTK_Class:
521 TagName = "class";
522 FixItTagName = "class ";
523 break;
524
525 case TTK_Enum:
526 TagName = "enum";
527 FixItTagName = "enum ";
528 break;
529
530 case TTK_Struct:
531 TagName = "struct";
532 FixItTagName = "struct ";
533 break;
534
Joao Matosdc86f942012-08-31 18:45:21 +0000535 case TTK_Interface:
536 TagName = "__interface";
537 FixItTagName = "__interface ";
538 break;
539
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000540 case TTK_Union:
541 TagName = "union";
542 FixItTagName = "union ";
543 break;
544 }
545
546 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
547 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
548 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
549
Richard Smithaa31b4b2012-09-06 01:37:56 +0000550 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
551 I != IEnd; ++I)
552 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
553 << Name << TagName;
554
555 // Replace lookup results with just the tag decl.
556 Result.clear(Sema::LookupTagName);
557 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000558 return true;
559 }
560
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000561 return false;
562}
563
Richard Smith4f605af2012-08-18 00:55:03 +0000564/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
565static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
566 QualType T, SourceLocation NameLoc) {
567 ASTContext &Context = S.Context;
568
569 TypeLocBuilder Builder;
570 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
571
572 T = S.getElaboratedType(ETK_None, SS, T);
573 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
574 ElabTL.setElaboratedKeywordLoc(SourceLocation());
575 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
576 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
577}
578
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000579Sema::NameClassification Sema::ClassifyName(Scope *S,
580 CXXScopeSpec &SS,
581 IdentifierInfo *&Name,
582 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000583 const Token &NextToken,
584 bool IsAddressOfOperand,
585 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000586 DeclarationNameInfo NameInfo(Name, NameLoc);
587 ObjCMethodDecl *CurMethod = getCurMethodDecl();
588
589 if (NextToken.is(tok::coloncolon)) {
590 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
591 QualType(), false, SS, 0, false);
592
593 }
594
595 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
596 LookupParsedName(Result, S, &SS, !CurMethod);
597
598 // Perform lookup for Objective-C instance variables (including automatically
599 // synthesized instance variables), if we're in an Objective-C method.
600 // FIXME: This lookup really, really needs to be folded in to the normal
601 // unqualified lookup mechanism.
602 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
603 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000604 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000605 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000606 }
607
608 bool SecondTry = false;
609 bool IsFilteredTemplateName = false;
610
611Corrected:
612 switch (Result.getResultKind()) {
613 case LookupResult::NotFound:
614 // If an unqualified-id is followed by a '(', then we have a function
615 // call.
616 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
617 // In C++, this is an ADL-only call.
618 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000619 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000620 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
621
622 // C90 6.3.2.2:
623 // If the expression that precedes the parenthesized argument list in a
624 // function call consists solely of an identifier, and if no
625 // declaration is visible for this identifier, the identifier is
626 // implicitly declared exactly as if, in the innermost block containing
627 // the function call, the declaration
628 //
629 // extern int identifier ();
630 //
631 // appeared.
632 //
633 // We also allow this in C99 as an extension.
634 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
635 Result.addDecl(D);
636 Result.resolveKind();
637 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
638 }
639 }
640
641 // In C, we first see whether there is a tag type by the same name, in
642 // which case it's likely that the user just forget to write "enum",
643 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000644 if (!getLangOpts().CPlusPlus && !SecondTry &&
645 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
646 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000647 }
648
649 // Perform typo correction to determine if there is another name that is
650 // close to this name.
Richard Smith4f605af2012-08-18 00:55:03 +0000651 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000652 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000653 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000654 Result.getLookupKind(), S,
Richard Smith4f605af2012-08-18 00:55:03 +0000655 &SS, *CCC)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000656 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
657 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000658
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000659 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000660 NamedDecl *UnderlyingFirstDecl
661 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000662 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000663 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000664 UnqualifiedDiag = diag::err_no_template_suggest;
665 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000666 } else if (UnderlyingFirstDecl &&
667 (isa<TypeDecl>(UnderlyingFirstDecl) ||
668 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
669 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000670 UnqualifiedDiag = diag::err_unknown_typename_suggest;
671 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
672 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000673
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000674 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000675 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000676 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000677 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
678 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000679 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000680 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
681 << Name << computeDeclContext(SS, false)
682 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000683 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000684
685 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000686 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000687
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000688 // Typo correction corrected to a keyword.
689 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000690 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000691
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000692 // Also update the LookupResult...
693 // FIXME: This should probably go away at some point
694 Result.clear();
695 Result.setLookupName(Corrected.getCorrection());
Richard Smithf9b15102013-08-17 00:46:16 +0000696 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000697 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000698
699 // If we found an Objective-C instance variable, let
700 // LookupInObjCMethod build the appropriate expression to
701 // reference the ivar.
702 // FIXME: This is a gross hack.
703 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
704 Result.clear();
705 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000706 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000707 }
708
709 goto Corrected;
710 }
711 }
712
713 // We failed to correct; just fall through and let the parser deal with it.
714 Result.suppressDiagnostics();
715 return NameClassification::Unknown();
716
Abramo Bagnara7945c982012-01-27 09:46:47 +0000717 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000718 // We performed name lookup into the current instantiation, and there were
719 // dependent bases, so we treat this result the same way as any other
720 // dependent nested-name-specifier.
721
722 // C++ [temp.res]p2:
723 // A name used in a template declaration or definition and that is
724 // dependent on a template-parameter is assumed not to name a type
725 // unless the applicable name lookup finds a type name or the name is
726 // qualified by the keyword typename.
727 //
728 // FIXME: If the next token is '<', we might want to ask the parser to
729 // perform some heroics to see if we actually have a
730 // template-argument-list, which would indicate a missing 'template'
731 // keyword here.
Richard Smith4f605af2012-08-18 00:55:03 +0000732 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
733 NameInfo, IsAddressOfOperand,
734 /*TemplateArgs=*/0);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000735 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000736
737 case LookupResult::Found:
738 case LookupResult::FoundOverloaded:
739 case LookupResult::FoundUnresolvedValue:
740 break;
741
742 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000743 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000744 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000745 // C++ [temp.local]p3:
746 // A lookup that finds an injected-class-name (10.2) can result in an
747 // ambiguity in certain cases (for example, if it is found in more than
748 // one base class). If all of the injected-class-names that are found
749 // refer to specializations of the same class template, and if the name
750 // is followed by a template-argument-list, the reference refers to the
751 // class template itself and not a specialization thereof, and is not
752 // ambiguous.
753 //
754 // This filtering can make an ambiguous result into an unambiguous one,
755 // so try again after filtering out template names.
756 FilterAcceptableTemplateNames(Result);
757 if (!Result.isAmbiguous()) {
758 IsFilteredTemplateName = true;
759 break;
760 }
761 }
762
763 // Diagnose the ambiguity and return an error.
764 return NameClassification::Error();
765 }
766
David Blaikiebbafb8a2012-03-11 07:00:24 +0000767 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000768 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
769 // C++ [temp.names]p3:
770 // After name lookup (3.4) finds that a name is a template-name or that
771 // an operator-function-id or a literal- operator-id refers to a set of
772 // overloaded functions any member of which is a function template if
773 // this is followed by a <, the < is always taken as the delimiter of a
774 // template-argument-list and never as the less-than operator.
775 if (!IsFilteredTemplateName)
776 FilterAcceptableTemplateNames(Result);
777
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000778 if (!Result.empty()) {
779 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000780 bool IsVarTemplate;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000781 TemplateName Template;
782 if (Result.end() - Result.begin() > 1) {
783 IsFunctionTemplate = true;
784 Template = Context.getOverloadedTemplateName(Result.begin(),
785 Result.end());
786 } else {
787 TemplateDecl *TD
788 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
789 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000790 IsVarTemplate = isa<VarTemplateDecl>(TD);
791
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000792 if (SS.isSet() && !SS.isInvalid())
793 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000794 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000795 TD);
796 else
797 Template = TemplateName(TD);
798 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000799
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000800 if (IsFunctionTemplate) {
801 // Function templates always go through overload resolution, at which
802 // point we'll perform the various checks (e.g., accessibility) we need
803 // to based on which function we selected.
804 Result.suppressDiagnostics();
805
806 return NameClassification::FunctionTemplate(Template);
807 }
Larisse Voufo39a1e502013-08-06 01:03:05 +0000808
809 return IsVarTemplate ? NameClassification::VarTemplate(Template)
810 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000811 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000812 }
Richard Smith4f605af2012-08-18 00:55:03 +0000813
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000814 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000815 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
816 DiagnoseUseOfDecl(Type, NameLoc);
817 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000818 if (SS.isNotEmpty())
819 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000820 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000821 }
Richard Smith4f605af2012-08-18 00:55:03 +0000822
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000823 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
824 if (!Class) {
825 // FIXME: It's unfortunate that we don't have a Type node for handling this.
826 if (ObjCCompatibleAliasDecl *Alias
827 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
828 Class = Alias->getClassInterface();
829 }
830
831 if (Class) {
832 DiagnoseUseOfDecl(Class, NameLoc);
833
834 if (NextToken.is(tok::period)) {
835 // Interface. <something> is parsed as a property reference expression.
836 // Just return "unknown" as a fall-through for now.
837 Result.suppressDiagnostics();
838 return NameClassification::Unknown();
839 }
840
841 QualType T = Context.getObjCInterfaceType(Class);
842 return ParsedType::make(T);
843 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000844
Richard Smith4f605af2012-08-18 00:55:03 +0000845 // We can have a type template here if we're classifying a template argument.
846 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
847 return NameClassification::TypeTemplate(
848 TemplateName(cast<TemplateDecl>(FirstDecl)));
849
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000850 // Check for a tag type hidden by a non-type decl in a few cases where it
851 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000852 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
853 if ((NextToken.is(tok::identifier) ||
Alp Tokera2794f92014-01-22 07:29:52 +0000854 (NextIsOp &&
855 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000856 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
857 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
858 DiagnoseUseOfDecl(Type, NameLoc);
859 QualType T = Context.getTypeDeclType(Type);
860 if (SS.isNotEmpty())
861 return buildNestedType(*this, SS, T, NameLoc);
862 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000863 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000864
Richard Smith4f605af2012-08-18 00:55:03 +0000865 if (FirstDecl->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000866 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000867
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000868 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
869 return BuildDeclarationNameExpr(SS, Result, ADL);
870}
871
John McCall5ed6e8f2009-08-18 00:00:49 +0000872// Determines the context to return to after temporarily entering a
873// context. This depends in an unnecessarily complicated way on the
874// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000875DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000876
John McCall5ed6e8f2009-08-18 00:00:49 +0000877 // Functions defined inline within classes aren't parsed until we've
878 // finished parsing the top-level class, so the top-level class is
879 // the context we'll need to return to.
Faisal Valibb9071e2013-12-04 22:43:08 +0000880 // A Lambda call operator whose parent is a class must not be treated
881 // as an inline member function. A Lambda can be used legally
882 // either as an in-class member initializer or a default argument. These
883 // are parsed once the class has been marked complete and so the containing
884 // context would be the nested class (when the lambda is defined in one);
885 // If the class is not complete, then the lambda is being used in an
886 // ill-formed fashion (such as to specify the width of a bit-field, or
887 // in an array-bound) - in which case we still want to return the
888 // lexically containing DC (which could be a nested class).
889 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +0000890 DC = DC->getLexicalParent();
891
892 // A function not defined within a class will always return to its
893 // lexical context.
894 if (!isa<CXXRecordDecl>(DC))
895 return DC;
896
897 // A C++ inline method/friend is parsed *after* the topmost class
898 // it was declared in is fully parsed ("complete"); the topmost
899 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000900 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000901 DC = RD;
902
903 // Return the declaration context of the topmost class the inline method is
904 // declared in.
905 return DC;
906 }
907
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000908 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000909}
910
Douglas Gregor91f84212008-12-11 16:49:14 +0000911void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000912 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000913 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000914 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000915 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000916}
917
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000918void Sema::PopDeclContext() {
919 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000920
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000921 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000922 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000923}
924
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000925/// EnterDeclaratorContext - Used when we must lookup names in the context
926/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000927///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000928void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000929 // C++0x [basic.lookup.unqual]p13:
930 // A name used in the definition of a static data member of class
931 // X (after the qualified-id of the static member) is looked up as
932 // if the name was used in a member function of X.
933 // C++0x [basic.lookup.unqual]p14:
934 // If a variable member of a namespace is defined outside of the
935 // scope of its namespace then any name used in the definition of
936 // the variable member (after the declarator-id) is looked up as
937 // if the definition of the variable member occurred in its
938 // namespace.
939 // Both of these imply that we should push a scope whose context
940 // is the semantic context of the declaration. We can't use
941 // PushDeclContext here because that context is not necessarily
942 // lexically contained in the current context. Fortunately,
943 // the containing scope should have the appropriate information.
944
945 assert(!S->getEntity() && "scope already has entity");
946
947#ifndef NDEBUG
948 Scope *Ancestor = S->getParent();
949 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
950 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
951#endif
952
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000953 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000954 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000955}
956
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000957void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000958 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000959
John McCall6df5fef2009-12-19 10:49:29 +0000960 // Switch back to the lexical context. The safety of this is
961 // enforced by an assert in EnterDeclaratorContext.
962 Scope *Ancestor = S->getParent();
963 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +0000964 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +0000965
966 // We don't need to do anything with the scope, which is going to
967 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000968}
969
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000970
971void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
Alp Tokera2794f92014-01-22 07:29:52 +0000972 // We assume that the caller has already called
973 // ActOnReenterTemplateScope so getTemplatedDecl() works.
974 FunctionDecl *FD = D->getAsFunction();
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000975 if (!FD)
976 return;
977
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000978 // Same implementation as PushDeclContext, but enters the context
979 // from the lexical parent, rather than the top-level class.
980 assert(CurContext == FD->getLexicalParent() &&
981 "The next DeclContext should be lexically contained in the current one.");
982 CurContext = FD;
983 S->setEntity(CurContext);
984
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000985 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
986 ParmVarDecl *Param = FD->getParamDecl(P);
987 // If the parameter has an identifier, then add it to the scope
988 if (Param->getIdentifier()) {
989 S->AddDecl(Param);
990 IdResolver.AddDecl(Param);
991 }
992 }
993}
994
995
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000996void Sema::ActOnExitFunctionContext() {
997 // Same implementation as PopDeclContext, but returns to the lexical parent,
998 // rather than the top-level class.
999 assert(CurContext && "DeclContext imbalance!");
1000 CurContext = CurContext->getLexicalParent();
1001 assert(CurContext && "Popped translation unit!");
1002}
1003
1004
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001005/// \brief Determine whether we allow overloading of the function
1006/// PrevDecl with another declaration.
1007///
1008/// This routine determines whether overloading is possible, not
1009/// whether some new function is actually an overload. It will return
1010/// true in C++ (where we can always provide overloads) or, as an
1011/// extension, in C when the previous function is already an
1012/// overloaded function declaration or has the "overloadable"
1013/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001014static bool AllowOverloadingOfFunction(LookupResult &Previous,
1015 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001016 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001017 return true;
1018
John McCall1f82f242009-11-18 22:49:29 +00001019 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001020 return true;
1021
John McCall1f82f242009-11-18 22:49:29 +00001022 return (Previous.getResultKind() == LookupResult::Found
1023 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001024}
1025
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001026/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001027void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001028 // Move up the scope chain until we find the nearest enclosing
1029 // non-transparent context. The declaration will be introduced into this
1030 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001031 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001032 S = S->getParent();
1033
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001034 // Add scoped declarations into their context, so that they can be
1035 // found later. Declarations without a context won't be inserted
1036 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001037 if (AddToContext)
1038 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001039
Richard Smith541b38b2013-09-20 01:15:31 +00001040 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1041 // are function-local declarations.
1042 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001043 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001044 D->getLexicalDeclContext()->getRedeclContext()) &&
1045 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001046 return;
1047
1048 // Template instantiations should also not be pushed into scope.
1049 if (isa<FunctionDecl>(D) &&
1050 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001051 return;
1052
John McCall9f3059a2009-10-09 21:13:30 +00001053 // If this replaces anything in the current scope,
1054 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1055 IEnd = IdResolver.end();
1056 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001057 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1058 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001059 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001060
John McCall9f3059a2009-10-09 21:13:30 +00001061 // Should only need to replace one decl.
1062 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001063 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001064 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001065
John McCall48871652010-08-21 09:40:31 +00001066 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001067
1068 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1069 // Implicitly-generated labels may end up getting generated in an order that
1070 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1071 // the label at the appropriate place in the identifier chain.
1072 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001073 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001074 if (IDC == CurContext) {
1075 if (!S->isDeclScope(*I))
1076 continue;
1077 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001078 break;
1079 }
1080
Douglas Gregor46c04e72011-03-16 16:39:03 +00001081 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001082 } else {
1083 IdResolver.AddDecl(D);
1084 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001085}
1086
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001087void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1088 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1089 TUScope->AddDecl(D);
1090}
1091
Richard Smith1c34fb72013-08-13 18:18:50 +00001092bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001093 bool AllowInlineNamespace) {
1094 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001095}
1096
John McCallcc14d1f2010-08-24 08:50:51 +00001097Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1098 DeclContext *TargetDC = DC->getPrimaryContext();
1099 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001100 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001101 if (ScopeDC->getPrimaryContext() == TargetDC)
1102 return S;
1103 } while ((S = S->getParent()));
1104
1105 return 0;
1106}
1107
John McCall1f82f242009-11-18 22:49:29 +00001108static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1109 DeclContext*,
1110 ASTContext&);
1111
1112/// Filters out lookup results that don't fall within the given scope
1113/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001114void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001115 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001116 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001117 LookupResult::Filter F = R.makeFilter();
1118 while (F.hasNext()) {
1119 NamedDecl *D = F.next();
1120
Richard Smith72bcaec2013-12-05 04:30:04 +00001121 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001122 continue;
1123
Richard Smith72bcaec2013-12-05 04:30:04 +00001124 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001125 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001126
John McCall1f82f242009-11-18 22:49:29 +00001127 F.erase();
1128 }
1129
1130 F.done();
1131}
1132
1133static bool isUsingDecl(NamedDecl *D) {
1134 return isa<UsingShadowDecl>(D) ||
1135 isa<UnresolvedUsingTypenameDecl>(D) ||
1136 isa<UnresolvedUsingValueDecl>(D);
1137}
1138
1139/// Removes using shadow declarations from the lookup results.
1140static void RemoveUsingDecls(LookupResult &R) {
1141 LookupResult::Filter F = R.makeFilter();
1142 while (F.hasNext())
1143 if (isUsingDecl(F.next()))
1144 F.erase();
1145
1146 F.done();
1147}
1148
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001149/// \brief Check for this common pattern:
1150/// @code
1151/// class S {
1152/// S(const S&); // DO NOT IMPLEMENT
1153/// void operator=(const S&); // DO NOT IMPLEMENT
1154/// };
1155/// @endcode
1156static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1157 // FIXME: Should check for private access too but access is set after we get
1158 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001159 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001160 return false;
1161
1162 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1163 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001164 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1165 return Method->isCopyAssignmentOperator();
1166 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001167}
1168
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001169// We need this to handle
1170//
1171// typedef struct {
1172// void *foo() { return 0; }
1173// } A;
1174//
1175// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1176// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001177// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001178// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001179// Callers should verify at the end of the TU if it D has external linkage or
1180// not.
1181bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1182 const DeclContext *DC = D->getDeclContext();
1183 while (!DC->isTranslationUnit()) {
1184 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1185 if (!RD->hasNameForLinkage())
1186 return true;
1187 }
1188 DC = DC->getParent();
1189 }
1190
Rafael Espindola3ae00052013-05-13 00:12:11 +00001191 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001192}
1193
Eli Friedman5ef21752013-09-10 03:05:56 +00001194// FIXME: This needs to be refactored; some other isInMainFile users want
1195// these semantics.
1196static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1197 if (S.TUKind != TU_Complete)
1198 return false;
1199 return S.SourceMgr.isInMainFile(Loc);
1200}
1201
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001202bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1203 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001204
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001205 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1206 return false;
1207
1208 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001209 if (D->getDeclContext()->isDependentContext() ||
1210 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001211 return false;
1212
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001213 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001214 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1215 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001216
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001217 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1218 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1219 return false;
1220 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001221 // 'static inline' functions are defined in headers; don't warn.
1222 if (FD->isInlineSpecified() &&
1223 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001224 return false;
1225 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001226
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001227 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001228 Context.DeclMustBeEmitted(FD))
1229 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001230 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001231 // Constants and utility variables are defined in headers with internal
1232 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1233 // like "inline".)
1234 if (!isMainFileLoc(*this, VD->getLocation()))
1235 return false;
1236
Eli Friedman5ef21752013-09-10 03:05:56 +00001237 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001238 return false;
1239
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001240 if (VD->isStaticDataMember() &&
1241 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1242 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001243 } else {
1244 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001245 }
1246
John McCalld37d35b2010-10-27 01:41:35 +00001247 // Only warn for unused decls internal to the translation unit.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001248 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001249}
1250
1251void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001252 if (!D)
1253 return;
1254
1255 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001256 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001257 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1258 return; // First should already be in the vector.
1259 }
1260
1261 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001262 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001263 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1264 return; // First should already be in the vector.
1265 }
1266
David Blaikie3d8edc22012-05-26 05:35:39 +00001267 if (ShouldWarnIfUnusedFileScopedDecl(D))
1268 UnusedFileScopedDecls.push_back(D);
1269}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001270
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001271static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001272 if (D->isInvalidDecl())
1273 return false;
1274
Ted Kremenekce0e3f82014-01-09 20:19:45 +00001275 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1276 D->hasAttr<ObjCPreciseLifetimeAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001277 return false;
John McCall67da35c2010-02-04 22:26:26 +00001278
Chris Lattnercab02a62011-02-17 20:34:02 +00001279 if (isa<LabelDecl>(D))
1280 return true;
1281
John McCall67da35c2010-02-04 22:26:26 +00001282 // White-list anything that isn't a local variable.
1283 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1284 !D->getDeclContext()->isFunctionOrMethod())
1285 return false;
1286
1287 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001288 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001289
1290 // White-list anything with an __attribute__((unused)) type.
1291 QualType Ty = VD->getType();
1292
1293 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001294 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001295 if (TT->getDecl()->hasAttr<UnusedAttr>())
1296 return false;
1297 }
1298
Douglas Gregor14f232e2010-05-08 23:05:03 +00001299 // If we failed to complete the type for some reason, or if the type is
1300 // dependent, don't diagnose the variable.
1301 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001302 return false;
1303
John McCallcef15822010-03-31 02:47:45 +00001304 if (const TagType *TT = Ty->getAs<TagType>()) {
1305 const TagDecl *Tag = TT->getDecl();
1306 if (Tag->hasAttr<UnusedAttr>())
1307 return false;
1308
1309 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001310 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001311 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001312
1313 if (const Expr *Init = VD->getInit()) {
David Blaikiea9d4a932012-10-24 21:29:06 +00001314 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1315 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001316 const CXXConstructExpr *Construct =
1317 dyn_cast<CXXConstructExpr>(Init);
1318 if (Construct && !Construct->isElidable()) {
1319 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001320 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001321 return false;
1322 }
1323 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001324 }
1325 }
John McCallcef15822010-03-31 02:47:45 +00001326
1327 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001328 }
1329
John McCall67da35c2010-02-04 22:26:26 +00001330 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001331}
1332
Anna Zaks964f4c62011-07-28 20:52:06 +00001333static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1334 FixItHint &Hint) {
1335 if (isa<LabelDecl>(D)) {
1336 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001337 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001338 if (AfterColon.isInvalid())
1339 return;
1340 Hint = FixItHint::CreateRemoval(CharSourceRange::
1341 getCharRange(D->getLocStart(), AfterColon));
1342 }
1343 return;
1344}
1345
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001346/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1347/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001348void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001349 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001350 if (!ShouldDiagnoseUnusedDecl(D))
1351 return;
1352
Anna Zaks964f4c62011-07-28 20:52:06 +00001353 GenerateFixForUnusedDecl(D, Context, Hint);
1354
Chris Lattnercab02a62011-02-17 20:34:02 +00001355 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001356 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001357 DiagID = diag::warn_unused_exception_param;
1358 else if (isa<LabelDecl>(D))
1359 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001360 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001361 DiagID = diag::warn_unused_variable;
1362
Anna Zaks964f4c62011-07-28 20:52:06 +00001363 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001364}
1365
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001366static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1367 // Verify that we have no forward references left. If so, there was a goto
1368 // or address of a label taken, but no definition of it. Label fwd
1369 // definitions are indicated with a null substmt.
1370 if (L->getStmt() == 0)
1371 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1372}
1373
Steve Naroffc62adb62007-10-09 22:01:59 +00001374void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001375 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001376 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001377 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001378
Chris Lattner302b4be2006-11-19 02:31:38 +00001379 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1380 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001381 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001382 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001383
Douglas Gregor91f84212008-12-11 16:49:14 +00001384 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1385 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001386
Douglas Gregor91f84212008-12-11 16:49:14 +00001387 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001388
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001389 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001390 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001391 DiagnoseUnusedDecl(D);
1392
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001393 // If this was a forward reference to a label, verify it was defined.
1394 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1395 CheckPoppedLabel(LD, *this);
1396
Douglas Gregor91f84212008-12-11 16:49:14 +00001397 // Remove this name from our lexical scope.
1398 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001399 }
1400}
1401
Douglas Gregor1c283312010-08-11 12:19:30 +00001402/// \brief Look for an Objective-C class in the translation unit.
1403///
1404/// \param Id The name of the Objective-C class we're looking for. If
1405/// typo-correction fixes this name, the Id will be updated
1406/// to the fixed name.
1407///
1408/// \param IdLoc The location of the name in the translation unit.
1409///
James Dennett41725122012-06-22 10:16:05 +00001410/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001411/// if there is no class with the given name.
1412///
1413/// \returns The declaration of the named Objective-C class, or NULL if the
1414/// class could not be found.
1415ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1416 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001417 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001418 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1419 // creation from this context.
1420 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1421
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001422 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001423 // Perform typo correction at the given location, but only if we
1424 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001425 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1426 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1427 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001428 Validator)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001429 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001430 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001431 Id = IDecl->getIdentifier();
1432 }
1433 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001434 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1435 // This routine must always return a class definition, if any.
1436 if (Def && Def->getDefinition())
1437 Def = Def->getDefinition();
1438 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001439}
1440
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001441/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1442/// from S, where a non-field would be declared. This routine copes
1443/// with the difference between C and C++ scoping rules in structs and
1444/// unions. For example, the following code is well-formed in C but
1445/// ill-formed in C++:
1446/// @code
1447/// struct S6 {
1448/// enum { BAR } e;
1449/// };
Mike Stump11289f42009-09-09 15:08:12 +00001450///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001451/// void test_S6() {
1452/// struct S6 a;
1453/// a.e = BAR;
1454/// }
1455/// @endcode
1456/// For the declaration of BAR, this routine will return a different
1457/// scope. The scope S will be the scope of the unnamed enumeration
1458/// within S6. In C++, this routine will return the scope associated
1459/// with S6, because the enumeration's scope is a transparent
1460/// context but structures can contain non-field names. In C, this
1461/// routine will return the translation unit scope, since the
1462/// enumeration's scope is a transparent context and structures cannot
1463/// contain non-field names.
1464Scope *Sema::getNonFieldDeclScope(Scope *S) {
1465 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001466 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001467 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001468 S = S->getParent();
1469 return S;
1470}
1471
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001472/// \brief Looks up the declaration of "struct objc_super" and
1473/// saves it for later use in building builtin declaration of
1474/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1475/// pre-existing declaration exists no action takes place.
1476static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1477 IdentifierInfo *II) {
1478 if (!II->isStr("objc_msgSendSuper"))
1479 return;
1480 ASTContext &Context = ThisSema.Context;
1481
1482 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1483 SourceLocation(), Sema::LookupTagName);
1484 ThisSema.LookupName(Result, S);
1485 if (Result.getResultKind() == LookupResult::Found)
1486 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1487 Context.setObjCSuperType(Context.getTagDeclType(TD));
1488}
1489
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001490/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1491/// file scope. lazily create a decl for it. ForRedeclaration is true
1492/// if we're creating this built-in in anticipation of redeclaring the
1493/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001494NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001495 Scope *S, bool ForRedeclaration,
1496 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001497 LookupPredefedObjCSuperType(*this, S, II);
1498
Chris Lattner9561a0b2007-01-28 08:20:04 +00001499 Builtin::ID BID = (Builtin::ID)bid;
1500
Chris Lattnerecd79c62009-06-14 00:45:47 +00001501 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001502 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001503 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001504 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001505 // Okay
1506 break;
1507
Mike Stump93246cc2009-07-28 23:57:15 +00001508 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001509 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001510 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001511 << Context.BuiltinInfo.GetName(BID);
1512 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001513
Mike Stump93246cc2009-07-28 23:57:15 +00001514 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001515 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001516 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001517 << Context.BuiltinInfo.GetName(BID);
1518 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001519
1520 case ASTContext::GE_Missing_ucontext:
1521 if (ForRedeclaration)
1522 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1523 << Context.BuiltinInfo.GetName(BID);
1524 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001525 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001526
1527 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1528 Diag(Loc, diag::ext_implicit_lib_function_decl)
1529 << Context.BuiltinInfo.GetName(BID)
1530 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001531 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001532 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001533 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001534 Diag(Loc, diag::note_please_include_header)
1535 << Context.BuiltinInfo.getHeaderName(BID)
1536 << Context.BuiltinInfo.GetName(BID);
1537 }
1538
Warren Hunt445d83e2013-11-01 23:46:51 +00001539 DeclContext *Parent = Context.getTranslationUnitDecl();
1540 if (getLangOpts().CPlusPlus) {
1541 LinkageSpecDecl *CLinkageDecl =
1542 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1543 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001544 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001545 Parent->addDecl(CLinkageDecl);
1546 Parent = CLinkageDecl;
1547 }
1548
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001549 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001550 Parent,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001551 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001552 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001553 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001554 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001555 New->setImplicit();
1556
Chris Lattner4dd27102008-05-05 22:18:14 +00001557 // Create Decl objects for each parameter, adding them to the
1558 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001559 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001560 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00001561 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001562 ParmVarDecl *parm =
Alp Toker9cacbab2014-01-20 20:26:09 +00001563 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1564 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001565 parm->setScopeInfo(0, i);
1566 Params.push_back(parm);
1567 }
David Blaikie9c70e042011-09-21 18:16:56 +00001568 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001569 }
Mike Stump11289f42009-09-09 15:08:12 +00001570
1571 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001572 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001574 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001575 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1576 // relate Scopes to DeclContexts, and probably eliminate CurContext
1577 // entirely, but we're not there yet.
1578 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001579 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001580 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001581 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001582 return New;
1583}
1584
Douglas Gregor3552dab2013-01-09 00:47:56 +00001585/// \brief Filter out any previous declarations that the given declaration
1586/// should not consider because they are not permitted to conflict, e.g.,
1587/// because they come from hidden sub-modules and do not refer to the same
1588/// entity.
1589static void filterNonConflictingPreviousDecls(ASTContext &context,
1590 NamedDecl *decl,
1591 LookupResult &previous){
1592 // This is only interesting when modules are enabled.
1593 if (!context.getLangOpts().Modules)
1594 return;
1595
1596 // Empty sets are uninteresting.
1597 if (previous.empty())
1598 return;
1599
Douglas Gregor3552dab2013-01-09 00:47:56 +00001600 LookupResult::Filter filter = previous.makeFilter();
1601 while (filter.hasNext()) {
1602 NamedDecl *old = filter.next();
1603
1604 // Non-hidden declarations are never ignored.
1605 if (!old->isHidden())
1606 continue;
1607
Rafael Espindola3ae00052013-05-13 00:12:11 +00001608 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001609 filter.erase();
1610 }
1611
1612 filter.done();
1613}
1614
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001615bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1616 QualType OldType;
1617 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1618 OldType = OldTypedef->getUnderlyingType();
1619 else
1620 OldType = Context.getTypeDeclType(Old);
1621 QualType NewType = New->getUnderlyingType();
1622
Douglas Gregoraab36982012-01-11 22:33:48 +00001623 if (NewType->isVariablyModifiedType()) {
1624 // Must not redefine a typedef with a variably-modified type.
1625 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1626 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1627 << Kind << NewType;
1628 if (Old->getLocation().isValid())
1629 Diag(Old->getLocation(), diag::note_previous_definition);
1630 New->setInvalidDecl();
1631 return true;
1632 }
1633
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001634 if (OldType != NewType &&
1635 !OldType->isDependentType() &&
1636 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001637 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001638 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1639 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1640 << Kind << NewType << OldType;
1641 if (Old->getLocation().isValid())
1642 Diag(Old->getLocation(), diag::note_previous_definition);
1643 New->setInvalidDecl();
1644 return true;
1645 }
1646 return false;
1647}
1648
Richard Smithdda56e42011-04-15 14:24:37 +00001649/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001650/// same name and scope as a previous declaration 'Old'. Figure out
1651/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001652/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001653///
Richard Smithdda56e42011-04-15 14:24:37 +00001654void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001655 // If the new decl is known invalid already, don't bother doing any
1656 // merging checks.
1657 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001658
Steve Naroff44cfcb62008-09-09 14:32:20 +00001659 // Allow multiple definitions for ObjC built-in typedefs.
1660 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001661 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001662 const IdentifierInfo *TypeID = New->getIdentifier();
1663 switch (TypeID->getLength()) {
1664 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001665 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001666 {
1667 if (!TypeID->isStr("id"))
1668 break;
1669 QualType T = New->getUnderlyingType();
1670 if (!T->isPointerType())
1671 break;
1672 if (!T->isVoidPointerType()) {
1673 QualType PT = T->getAs<PointerType>()->getPointeeType();
1674 if (!PT->isStructureType())
1675 break;
1676 }
1677 Context.setObjCIdRedefinitionType(T);
1678 // Install the built-in type for 'id', ignoring the current definition.
1679 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1680 return;
1681 }
Chris Lattner66e32812008-11-20 05:41:43 +00001682 case 5:
1683 if (!TypeID->isStr("Class"))
1684 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001685 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001686 // Install the built-in type for 'Class', ignoring the current definition.
1687 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001688 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001689 case 3:
1690 if (!TypeID->isStr("SEL"))
1691 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001692 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001693 // Install the built-in type for 'SEL', ignoring the current definition.
1694 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001695 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001696 }
1697 // Fall through - the typedef name was not a builtin type.
1698 }
John McCall1f82f242009-11-18 22:49:29 +00001699
Douglas Gregorfb034662009-01-28 17:15:10 +00001700 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001701 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1702 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001703 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001704 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001705
1706 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001707 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001708 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001709
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001710 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001711 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001712
John McCall1f82f242009-11-18 22:49:29 +00001713 // If the old declaration is invalid, just give up here.
1714 if (Old->isInvalidDecl())
1715 return New->setInvalidDecl();
1716
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001717 // If the typedef types are not identical, reject them in all languages and
1718 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001719 if (isIncompatibleTypedef(Old, New))
1720 return;
Mike Stump11289f42009-09-09 15:08:12 +00001721
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001722 // The types match. Link up the redeclaration chain and merge attributes if
1723 // the old declaration was a typedef.
1724 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001725 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001726 mergeDeclAttributes(New, Old);
1727 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001728
David Blaikiebbafb8a2012-03-11 07:00:24 +00001729 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001730 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001731
David Blaikiebbafb8a2012-03-11 07:00:24 +00001732 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001733 // C++ [dcl.typedef]p2:
1734 // In a given non-class scope, a typedef specifier can be used to
1735 // redefine the name of any type declared in that scope to refer
1736 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001737 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001738 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001739
1740 // C++0x [dcl.typedef]p4:
1741 // In a given class scope, a typedef specifier can be used to redefine
1742 // any class-name declared in that scope that is not also a typedef-name
1743 // to refer to the type to which it already refers.
1744 //
1745 // This wording came in via DR424, which was a correction to the
1746 // wording in DR56, which accidentally banned code like:
1747 //
1748 // struct S {
1749 // typedef struct A { } A;
1750 // };
1751 //
1752 // in the C++03 standard. We implement the C++0x semantics, which
1753 // allow the above but disallow
1754 //
1755 // struct S {
1756 // typedef int I;
1757 // typedef int I;
1758 // };
1759 //
1760 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001761 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001762 return;
1763
Chris Lattner2581fc32009-04-17 22:04:20 +00001764 Diag(New->getLocation(), diag::err_redefinition)
1765 << New->getDeclName();
1766 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001767 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001768 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001769
Douglas Gregor7363fb02012-01-11 04:25:01 +00001770 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001771 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001772 return;
1773
Chris Lattner2581fc32009-04-17 22:04:20 +00001774 // If we have a redefinition of a typedef in C, emit a warning. This warning
1775 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001776 // -Wtypedef-redefinition. If either the original or the redefinition is
1777 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001778 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001779 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1780 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001781 return;
Mike Stump11289f42009-09-09 15:08:12 +00001782
Chris Lattner2581fc32009-04-17 22:04:20 +00001783 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1784 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001785 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001786 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001787}
1788
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001789/// DeclhasAttr - returns true if decl Declaration already has the target
1790/// attribute.
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001791static bool DeclHasAttr(const Decl *D, const Attr *A) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001792 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001793 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001794 for (const auto *i : D->attrs())
1795 if (i->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001796 if (Ann) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001797 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001798 return true;
1799 continue;
1800 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001801 // FIXME: Don't hardcode this check
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001802 if (OA && isa<OwnershipAttr>(i))
1803 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001804 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001805 }
Chris Lattner84966392008-03-03 03:28:21 +00001806
1807 return false;
1808}
1809
Richard Smithbc8caaf2013-02-22 04:55:39 +00001810static bool isAttributeTargetADefinition(Decl *D) {
1811 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1812 return VD->isThisDeclarationADefinition();
1813 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1814 return TD->isCompleteDefinition() || TD->isBeingDefined();
1815 return true;
1816}
1817
1818/// Merge alignment attributes from \p Old to \p New, taking into account the
1819/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1820///
1821/// \return \c true if any attributes were added to \p New.
1822static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1823 // Look for alignas attributes on Old, and pick out whichever attribute
1824 // specifies the strictest alignment requirement.
1825 AlignedAttr *OldAlignasAttr = 0;
1826 AlignedAttr *OldStrictestAlignAttr = 0;
1827 unsigned OldAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001828 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001829 // FIXME: We have no way of representing inherited dependent alignments
1830 // in a case like:
1831 // template<int A, int B> struct alignas(A) X;
1832 // template<int A, int B> struct alignas(B) X {};
1833 // For now, we just ignore any alignas attributes which are not on the
1834 // definition in such a case.
1835 if (I->isAlignmentDependent())
1836 return false;
1837
1838 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001839 OldAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001840
1841 unsigned Align = I->getAlignment(S.Context);
1842 if (Align > OldAlign) {
1843 OldAlign = Align;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001844 OldStrictestAlignAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001845 }
1846 }
1847
1848 // Look for alignas attributes on New.
1849 AlignedAttr *NewAlignasAttr = 0;
1850 unsigned NewAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001851 for (auto *I : New->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001852 if (I->isAlignmentDependent())
1853 return false;
1854
1855 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001856 NewAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001857
1858 unsigned Align = I->getAlignment(S.Context);
1859 if (Align > NewAlign)
1860 NewAlign = Align;
1861 }
1862
1863 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1864 // Both declarations have 'alignas' attributes. We require them to match.
1865 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1866 // fall short. (If two declarations both have alignas, they must both match
1867 // every definition, and so must match each other if there is a definition.)
1868
1869 // If either declaration only contains 'alignas(0)' specifiers, then it
1870 // specifies the natural alignment for the type.
1871 if (OldAlign == 0 || NewAlign == 0) {
1872 QualType Ty;
1873 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1874 Ty = VD->getType();
1875 else
1876 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1877
1878 if (OldAlign == 0)
1879 OldAlign = S.Context.getTypeAlign(Ty);
1880 if (NewAlign == 0)
1881 NewAlign = S.Context.getTypeAlign(Ty);
1882 }
1883
1884 if (OldAlign != NewAlign) {
1885 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1886 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1887 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1888 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1889 }
1890 }
1891
1892 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1893 // C++11 [dcl.align]p6:
1894 // if any declaration of an entity has an alignment-specifier,
1895 // every defining declaration of that entity shall specify an
1896 // equivalent alignment.
1897 // C11 6.7.5/7:
1898 // If the definition of an object does not have an alignment
1899 // specifier, any other declaration of that object shall also
1900 // have no alignment specifier.
1901 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001902 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001903 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001904 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001905 }
1906
1907 bool AnyAdded = false;
1908
1909 // Ensure we have an attribute representing the strictest alignment.
1910 if (OldAlign > NewAlign) {
1911 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1912 Clone->setInherited(true);
1913 New->addAttr(Clone);
1914 AnyAdded = true;
1915 }
1916
1917 // Ensure we have an alignas attribute if the old declaration had one.
1918 if (OldAlignasAttr && !NewAlignasAttr &&
1919 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1920 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1921 Clone->setInherited(true);
1922 New->addAttr(Clone);
1923 AnyAdded = true;
1924 }
1925
1926 return AnyAdded;
1927}
1928
1929static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1930 bool Override) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001931 InheritableAttr *NewAttr = NULL;
Michael Han99315932013-01-24 16:46:58 +00001932 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola19de5612013-01-12 06:42:30 +00001933 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001934 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1935 AA->getIntroduced(), AA->getDeprecated(),
1936 AA->getObsoleted(), AA->getUnavailable(),
1937 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001938 AttrSpellingListIndex);
Richard Smithbc8caaf2013-02-22 04:55:39 +00001939 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1940 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1941 AttrSpellingListIndex);
1942 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1943 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1944 AttrSpellingListIndex);
Rafael Espindola19de5612013-01-12 06:42:30 +00001945 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001946 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1947 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001948 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001949 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1950 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001951 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001952 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1953 FA->getFormatIdx(), FA->getFirstArg(),
1954 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001955 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001956 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1957 AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00001958 else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr))
David Majnemer4bb09802014-02-10 19:50:15 +00001959 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
1960 AttrSpellingListIndex,
David Majnemer2c4e00a2014-01-29 22:07:36 +00001961 IA->getSemanticSpelling());
Richard Smithbc8caaf2013-02-22 04:55:39 +00001962 else if (isa<AlignedAttr>(Attr))
1963 // AlignedAttrs are handled separately, because we need to handle all
1964 // such attributes on a declaration at the same time.
1965 NewAttr = 0;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001966 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001967 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001968
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001969 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001970 NewAttr->setInherited(true);
1971 D->addAttr(NewAttr);
1972 return true;
1973 }
1974
1975 return false;
1976}
1977
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001978static const Decl *getDefinition(const Decl *D) {
1979 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00001980 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001981 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1982 const VarDecl *Def = VD->getDefinition();
1983 if (Def)
1984 return Def;
1985 return VD->getActingDefinition();
1986 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001987 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00001988 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001989 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00001990 return Def;
1991 }
1992 return NULL;
1993}
1994
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001995static bool hasAttribute(const Decl *D, attr::Kind Kind) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001996 for (const auto *Attribute : D->attrs())
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001997 if (Attribute->getKind() == Kind)
1998 return true;
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001999 return false;
2000}
2001
2002/// checkNewAttributesAfterDef - If we already have a definition, check that
2003/// there are no new attributes in this declaration.
2004static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2005 if (!New->hasAttrs())
2006 return;
2007
2008 const Decl *Def = getDefinition(Old);
2009 if (!Def || Def == New)
2010 return;
2011
2012 AttrVec &NewAttributes = New->getAttrs();
2013 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2014 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002015
2016 if (isa<AliasAttr>(NewAttribute)) {
2017 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2018 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2019 else {
2020 VarDecl *VD = cast<VarDecl>(New);
2021 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2022 VarDecl::TentativeDefinition
2023 ? diag::err_alias_after_tentative
2024 : diag::err_redefinition;
2025 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2026 S.Diag(Def->getLocation(), diag::note_previous_definition);
2027 VD->setInvalidDecl();
2028 }
2029 ++I;
2030 continue;
2031 }
2032
2033 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2034 // Tentative definitions are only interesting for the alias check above.
2035 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2036 ++I;
2037 continue;
2038 }
2039 }
2040
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002041 if (hasAttribute(Def, NewAttribute->getKind())) {
2042 ++I;
2043 continue; // regular attr merging will take care of validating this.
2044 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002045
Richard Smithdebc59d2013-01-30 05:45:05 +00002046 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002047 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002048 ++I;
2049 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002050 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2051 if (AA->isAlignas()) {
2052 // C++11 [dcl.align]p6:
2053 // if any declaration of an entity has an alignment-specifier,
2054 // every defining declaration of that entity shall specify an
2055 // equivalent alignment.
2056 // C11 6.7.5/7:
2057 // If the definition of an object does not have an alignment
2058 // specifier, any other declaration of that object shall also
2059 // have no alignment specifier.
2060 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002061 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002062 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002063 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002064 NewAttributes.erase(NewAttributes.begin() + I);
2065 --E;
2066 continue;
2067 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002068 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002069
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002070 S.Diag(NewAttribute->getLocation(),
2071 diag::warn_attribute_precede_definition);
2072 S.Diag(Def->getLocation(), diag::note_previous_definition);
2073 NewAttributes.erase(NewAttributes.begin() + I);
2074 --E;
2075 }
2076}
2077
John McCallf79e87d2011-03-02 04:00:57 +00002078/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002079void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002080 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002081 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2082 UsedAttr *NewAttr = OldAttr->clone(Context);
2083 NewAttr->setInherited(true);
2084 New->addAttr(NewAttr);
2085 }
2086
Richard Smithe233fbf2013-01-28 22:42:45 +00002087 if (!Old->hasAttrs() && !New->hasAttrs())
2088 return;
2089
Rafael Espindola36191042012-05-18 01:47:00 +00002090 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002091 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002092
Douglas Gregor32c17572012-01-01 20:30:41 +00002093 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002094 return;
John McCallf79e87d2011-03-02 04:00:57 +00002095
Douglas Gregor32c17572012-01-01 20:30:41 +00002096 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002097
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002098 // Ensure that any moving of objects within the allocated map is done before
2099 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002100 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002101
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002102 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002103 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002104 // Ignore deprecated/unavailable/availability attributes if requested.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002105 if (isa<DeprecatedAttr>(I) ||
2106 isa<UnavailableAttr>(I) ||
2107 isa<AvailabilityAttr>(I)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002108 switch (AMK) {
2109 case AMK_None:
2110 continue;
John McCalld2930c22011-07-22 02:45:48 +00002111
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002112 case AMK_Redeclaration:
2113 break;
2114
2115 case AMK_Override:
2116 Override = true;
2117 break;
2118 }
2119 }
2120
Rafael Espindolab0938852013-10-25 01:28:12 +00002121 // Already handled.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002122 if (isa<UsedAttr>(I))
Rafael Espindolab0938852013-10-25 01:28:12 +00002123 continue;
2124
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002125 if (mergeDeclAttribute(*this, New, I, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002126 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002127 }
John McCallf79e87d2011-03-02 04:00:57 +00002128
Richard Smithbc8caaf2013-02-22 04:55:39 +00002129 if (mergeAlignedAttrs(*this, New, Old))
2130 foundAny = true;
2131
Douglas Gregor32c17572012-01-01 20:30:41 +00002132 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002133}
2134
2135/// mergeParamDeclAttributes - Copy attributes from the old parameter
2136/// to the new one.
2137static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2138 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002139 Sema &S) {
2140 // C++11 [dcl.attr.depend]p2:
2141 // The first declaration of a function shall specify the
2142 // carries_dependency attribute for its declarator-id if any declaration
2143 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002144 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2145 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2146 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002147 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2148 // Find the first declaration of the parameter.
2149 // FIXME: Should we build redeclaration chains for function parameters?
2150 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002151 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002152 const ParmVarDecl *FirstVD =
2153 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2154 S.Diag(FirstVD->getLocation(),
2155 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2156 }
2157
John McCallf79e87d2011-03-02 04:00:57 +00002158 if (!oldDecl->hasAttrs())
2159 return;
2160
2161 bool foundAny = newDecl->hasAttrs();
2162
2163 // Ensure that any moving of objects within the allocated map is
2164 // done before we process them.
2165 if (!foundAny) newDecl->setAttrs(AttrVec());
2166
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002167 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2168 if (!DeclHasAttr(newDecl, I)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002169 InheritableAttr *newAttr =
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002170 cast<InheritableParamAttr>(I->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002171 newAttr->setInherited(true);
2172 newDecl->addAttr(newAttr);
2173 foundAny = true;
2174 }
2175 }
2176
2177 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002178}
2179
Dan Gohman28ade552010-07-26 21:25:24 +00002180namespace {
2181
Douglas Gregora74a2972009-03-06 22:43:54 +00002182/// Used in MergeFunctionDecl to keep track of function parameters in
2183/// C.
2184struct GNUCompatibleParamWarning {
2185 ParmVarDecl *OldParm;
2186 ParmVarDecl *NewParm;
2187 QualType PromotedType;
2188};
2189
Dan Gohman28ade552010-07-26 21:25:24 +00002190}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002191
2192/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002193Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002194 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002195 if (Ctor->isDefaultConstructor())
2196 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002197
2198 if (Ctor->isCopyConstructor())
2199 return Sema::CXXCopyConstructor;
2200
2201 if (Ctor->isMoveConstructor())
2202 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002203 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002204 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002205 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002206 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002207 } else if (MD->isMoveAssignmentOperator()) {
2208 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002209 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002210
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002211 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002212}
2213
Sebastian Redl243d9052010-06-09 21:17:41 +00002214/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002215/// only extern inline functions can be redefined, and even then only in
2216/// GNU89 mode.
2217static bool canRedefineFunction(const FunctionDecl *FD,
2218 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002219 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2220 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002221 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002222 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002223}
2224
Reid Kleckner78af0702013-08-27 23:08:25 +00002225const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2226 const AttributedType *AT = T->getAs<AttributedType>();
2227 while (AT && !AT->isCallingConv())
2228 AT = AT->getModifiedType()->getAs<AttributedType>();
2229 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002230}
2231
Benjamin Kramer3e350262013-02-15 12:30:38 +00002232template <typename T>
2233static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002234 const DeclContext *DC = Old->getDeclContext();
2235 if (DC->isRecord())
2236 return false;
2237
2238 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002239 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002240 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002241 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002242 return true;
2243 return false;
2244}
2245
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002246/// MergeFunctionDecl - We just parsed a function 'New' from
2247/// declarator D which has the same name and scope as a previous
2248/// declaration 'Old'. Figure out how to resolve this situation,
2249/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002250///
2251/// In C++, New and Old must be declarations that are not
2252/// overloaded. Use IsOverload to determine whether New and Old are
2253/// overloaded, and to select the Old declaration that New should be
2254/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002255///
2256/// Returns true if there was an error, false otherwise.
Richard Smith18819302014-02-06 01:31:33 +00002257bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2258 Scope *S, bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002259 // Verify the old decl was also a function.
Alp Tokera2794f92014-01-22 07:29:52 +00002260 FunctionDecl *Old = OldD->getAsFunction();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002261 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002262 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002263 if (New->getFriendObjectKind()) {
2264 Diag(New->getLocation(), diag::err_using_decl_friend);
2265 Diag(Shadow->getTargetDecl()->getLocation(),
2266 diag::note_using_decl_target);
2267 Diag(Shadow->getUsingDecl()->getLocation(),
2268 diag::note_using_decl) << 0;
2269 return true;
2270 }
2271
Richard Smith18819302014-02-06 01:31:33 +00002272 // C++11 [namespace.udecl]p14:
2273 // If a function declaration in namespace scope or block scope has the
2274 // same name and the same parameter-type-list as a function introduced
2275 // by a using-declaration, and the declarations do not declare the same
2276 // function, the program is ill-formed.
2277
2278 // Check whether the two declarations might declare the same function.
2279 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2280 if (Old &&
2281 !Old->getDeclContext()->getRedeclContext()->Equals(
2282 New->getDeclContext()->getRedeclContext()) &&
2283 !(Old->isExternC() && New->isExternC()))
2284 Old = 0;
2285
2286 if (!Old) {
2287 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2288 Diag(Shadow->getTargetDecl()->getLocation(),
2289 diag::note_using_decl_target);
2290 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2291 return true;
2292 }
2293 OldD = Old;
2294 } else {
2295 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2296 << New->getDeclName();
2297 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCalle29c5cd2009-12-10 19:51:03 +00002298 return true;
2299 }
Chris Lattnerc511efb2007-01-27 19:32:14 +00002300 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002301
David Majnemerea5092a2013-07-07 23:49:50 +00002302 // If the old declaration is invalid, just give up here.
2303 if (Old->isInvalidDecl())
2304 return true;
2305
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002306 // Determine whether the previous declaration was a definition,
2307 // implicit declaration, or a declaration.
2308 diag::kind PrevDiag;
Richard Smithbdd14642014-02-04 01:14:30 +00002309 SourceLocation OldLocation = Old->getLocation();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002310 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002311 PrevDiag = diag::note_previous_definition;
Richard Smithbdd14642014-02-04 01:14:30 +00002312 else if (Old->isImplicit()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002313 PrevDiag = diag::note_previous_implicit_declaration;
Richard Smithbdd14642014-02-04 01:14:30 +00002314 if (OldLocation.isInvalid())
2315 OldLocation = New->getLocation();
2316 } else
Chris Lattner0369c572008-11-23 23:12:31 +00002317 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002318
Charles Davisfea48452010-02-18 02:00:42 +00002319 // Don't complain about this if we're in GNU89 mode and the old function
2320 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002321 // Don't complain about specializations. They are not supposed to have
2322 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002323 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002324 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002325 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002326 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002327 !canRedefineFunction(Old, getLangOpts())) {
2328 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002329 Diag(New->getLocation(), diag::warn_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002330 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002331 } else {
2332 Diag(New->getLocation(), diag::err_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002333 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002334 return true;
2335 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002336 }
2337
Reid Kleckner78af0702013-08-27 23:08:25 +00002338
2339 // If a function is first declared with a calling convention, but is later
2340 // declared or defined without one, all following decls assume the calling
2341 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002342 //
John McCalla5f46fb2012-08-25 02:00:03 +00002343 // It's OK if a function is first declared without a calling convention,
2344 // but is later declared or defined with the default calling convention.
2345 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002346 // To test if either decl has an explicit calling convention, we look for
2347 // AttributedType sugar nodes on the type as written. If they are missing or
2348 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002349 //
2350 // Note also that we DO NOT return at this point, because we still have
2351 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002352 QualType OldQType = Context.getCanonicalType(Old->getType());
2353 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002354 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002355 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002356 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2357 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2358 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002359
Reid Kleckner78af0702013-08-27 23:08:25 +00002360 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002361 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002362 const FunctionType *FT =
2363 First->getType().getCanonicalType()->castAs<FunctionType>();
2364 FunctionType::ExtInfo FI = FT->getExtInfo();
2365 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2366 if (!NewCCExplicit) {
2367 // Inherit the CC from the previous declaration if it was specified
2368 // there but not here.
2369 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2370 RequiresAdjustment = true;
2371 } else {
2372 // Calling conventions aren't compatible, so complain.
2373 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2374 Diag(New->getLocation(), diag::err_cconv_change)
2375 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2376 << !FirstCCExplicit
2377 << (!FirstCCExplicit ? "" :
2378 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002379
Reid Kleckner78af0702013-08-27 23:08:25 +00002380 // Put the note on the first decl, since it is the one that matters.
2381 Diag(First->getLocation(), diag::note_previous_declaration);
2382 return true;
2383 }
John McCallcddbad02010-02-04 05:44:44 +00002384 }
2385
John McCallab26cfa2010-02-05 21:31:56 +00002386 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002387 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2388 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2389 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002390 }
2391
Douglas Gregor77e274f2010-06-18 21:30:25 +00002392 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002393 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2394 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2395 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002396 Diag(New->getLocation(), diag::err_regparm_mismatch)
2397 << NewType->getRegParmType()
2398 << OldType->getRegParmType();
Richard Smithbdd14642014-02-04 01:14:30 +00002399 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002400 return true;
2401 }
John McCall4f5019e2010-12-19 02:44:49 +00002402
2403 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2404 RequiresAdjustment = true;
2405 }
2406
Douglas Gregorf1404d72011-10-14 15:55:40 +00002407 // Merge ns_returns_retained attribute.
2408 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2409 if (NewTypeInfo.getProducesResult()) {
2410 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
Richard Smithbdd14642014-02-04 01:14:30 +00002411 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregorf1404d72011-10-14 15:55:40 +00002412 return true;
2413 }
2414
2415 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2416 RequiresAdjustment = true;
2417 }
2418
John McCall4f5019e2010-12-19 02:44:49 +00002419 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002420 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2421 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2422 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002423 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002424 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002425 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002426
2427 // If this redeclaration makes the function inline, we may need to add it to
2428 // UndefinedButUsed.
2429 if (!Old->isInlined() && New->isInlined() &&
2430 !New->hasAttr<GNUInlineAttr>() &&
2431 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2432 Old->isUsed(false) &&
2433 !Old->isDefined() && !New->isThisDeclarationADefinition())
2434 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2435 SourceLocation()));
2436
2437 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2438 // about it.
2439 if (New->hasAttr<GNUInlineAttr>() &&
2440 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2441 UndefinedButUsed.erase(Old->getCanonicalDecl());
2442 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002443
David Blaikiebbafb8a2012-03-11 07:00:24 +00002444 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002445 // (C++98 13.1p2):
2446 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002447 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002448 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002449
2450 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002451 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002452 // Redeclarations or specializations of a function or function template
2453 // with a declared return type that uses a placeholder type shall also
2454 // use that placeholder, not a deduced type.
Alp Toker314cc812014-01-25 16:55:45 +00002455 QualType OldDeclaredReturnType =
2456 (Old->getTypeSourceInfo()
2457 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2458 : OldType)->getReturnType();
2459 QualType NewDeclaredReturnType =
2460 (New->getTypeSourceInfo()
2461 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2462 : NewType)->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002463 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002464 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2465 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2466 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002467 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2468 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002469 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2470 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002471 if (New->isCXXClassMember() && New->isOutOfLine())
2472 Diag(New->getLocation(),
2473 diag::err_member_def_does_not_match_ret_type) << New;
2474 else
2475 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Richard Smithbdd14642014-02-04 01:14:30 +00002476 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002477 return true;
2478 }
2479 else
2480 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002481 }
2482
Alp Toker314cc812014-01-25 16:55:45 +00002483 QualType OldReturnType = OldType->getReturnType();
2484 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002485 if (OldReturnType != NewReturnType) {
2486 // If this function has a deduced return type and has already been
2487 // defined, copy the deduced value from the old declaration.
Alp Toker314cc812014-01-25 16:55:45 +00002488 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002489 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002490 New->setType(
2491 SubstAutoType(New->getType(),
2492 OldAT->isDependentType() ? Context.DependentTy
2493 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002494 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002495 SubstAutoType(NewQType,
2496 OldAT->isDependentType() ? Context.DependentTy
2497 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002498 }
2499 }
2500
2501 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2502 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002503 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002504 // Preserve triviality.
2505 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002506
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002507 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002508 // 2 CXXMethodDecls referring to the same function will be injected.
2509 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002510 bool IsClassScopeExplicitSpecialization =
2511 OldMethod->isFunctionTemplateSpecialization() &&
2512 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002513 bool isFriend = NewMethod->getFriendObjectKind();
2514
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002515 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2516 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002517 // -- Member function declarations with the same name and the
2518 // same parameter types cannot be overloaded if any of them
2519 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002520 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002521 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Richard Smithbdd14642014-02-04 01:14:30 +00002522 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002523 return true;
2524 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002525
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002526 // C++ [class.mem]p1:
2527 // [...] A member shall not be declared twice in the
2528 // member-specification, except that a nested class or member
2529 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002530 if (ActiveTemplateInstantiations.empty()) {
2531 unsigned NewDiag;
2532 if (isa<CXXConstructorDecl>(OldMethod))
2533 NewDiag = diag::err_constructor_redeclared;
2534 else if (isa<CXXDestructorDecl>(NewMethod))
2535 NewDiag = diag::err_destructor_redeclared;
2536 else if (isa<CXXConversionDecl>(NewMethod))
2537 NewDiag = diag::err_conv_function_redeclared;
2538 else
2539 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002540
Richard Smith57e7ff92012-07-13 04:12:04 +00002541 Diag(New->getLocation(), NewDiag);
2542 } else {
2543 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2544 << New << New->getType();
2545 }
Richard Smithbdd14642014-02-04 01:14:30 +00002546 Diag(OldLocation, PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002547
2548 // Complain if this is an explicit declaration of a special
2549 // member that was initially declared implicitly.
2550 //
2551 // As an exception, it's okay to befriend such methods in order
2552 // to permit the implicit constructor/destructor/operator calls.
2553 } else if (OldMethod->isImplicit()) {
2554 if (isFriend) {
2555 NewMethod->setImplicit();
2556 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002557 Diag(NewMethod->getLocation(),
2558 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002559 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002560 return true;
2561 }
Richard Smith337a5a12012-06-08 01:30:54 +00002562 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002563 Diag(NewMethod->getLocation(),
2564 diag::err_definition_of_explicitly_defaulted_member)
2565 << getSpecialMember(OldMethod);
2566 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002567 }
2568 }
2569
Richard Smith10876ef2013-01-17 01:30:42 +00002570 // C++11 [dcl.attr.noreturn]p1:
2571 // The first declaration of a function shall specify the noreturn
2572 // attribute if any declaration of that function specifies the noreturn
2573 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002574 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2575 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2576 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002577 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002578 diag::note_noreturn_missing_first_decl);
2579 }
2580
Richard Smithe233fbf2013-01-28 22:42:45 +00002581 // C++11 [dcl.attr.depend]p2:
2582 // The first declaration of a function shall specify the
2583 // carries_dependency attribute for its declarator-id if any declaration
2584 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002585 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2586 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2587 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002588 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002589 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002590 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2591 }
2592
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002593 // (C++98 8.3.5p3):
2594 // All declarations for a function shall agree exactly in both the
2595 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002596 // We also want to respect all the extended bits except noreturn.
2597
2598 // noreturn should now match unless the old type info didn't have it.
2599 QualType OldQTypeForComparison = OldQType;
2600 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2601 assert(OldQType == QualType(OldType, 0));
2602 const FunctionType *OldTypeForComparison
2603 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2604 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2605 assert(OldQTypeForComparison.isCanonical());
2606 }
2607
Rafael Espindolaf4187652013-02-14 01:18:37 +00002608 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002609 // As a special case, retain the language linkage from previous
2610 // declarations of a friend function as an extension.
2611 //
2612 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2613 // and is useful because there's otherwise no way to specify language
2614 // linkage within class scope.
2615 //
2616 // Check cautiously as the friend object kind isn't yet complete.
2617 if (New->getFriendObjectKind() != Decl::FOK_None) {
2618 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002619 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002620 } else {
2621 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002622 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002623 return true;
2624 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002625 }
2626
John McCall4f5019e2010-12-19 02:44:49 +00002627 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002628 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002629
Richard Smith541b38b2013-09-20 01:15:31 +00002630 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2631 New->isLocalExternDecl()) {
2632 // It's OK if we couldn't merge types for a local function declaraton
2633 // if either the old or new type is dependent. We'll merge the types
2634 // when we instantiate the function.
2635 return false;
2636 }
2637
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002638 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002639 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002640
2641 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002642 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002643 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002644 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002645 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2646 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002647 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002648 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002649 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002650 // The old declaration provided a function prototype, but the
2651 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002652 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Alp Toker9cacbab2014-01-20 20:26:09 +00002653 SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(),
2654 OldProto->param_type_end());
Alp Toker314cc812014-01-25 16:55:45 +00002655 NewQType =
2656 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2657 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002658 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002659 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002660
2661 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002662 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00002663 for (FunctionProtoType::param_type_iterator
2664 ParamType = OldProto->param_type_begin(),
2665 ParamEnd = OldProto->param_type_end();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002666 ParamType != ParamEnd; ++ParamType) {
2667 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002668 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002669 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002670 *ParamType, /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002671 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002672 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002673 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002674 Param->setImplicit();
2675 Params.push_back(Param);
2676 }
2677
David Blaikie9c70e042011-09-21 18:16:56 +00002678 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002679 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002680
Richard Smith1c34fb72013-08-13 18:18:50 +00002681 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002682 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002683
Douglas Gregora74a2972009-03-06 22:43:54 +00002684 // GNU C permits a K&R definition to follow a prototype declaration
2685 // if the declared types of the parameters in the K&R definition
2686 // match the types in the prototype declaration, even when the
2687 // promoted types of the parameters from the K&R definition differ
2688 // from the types in the prototype. GCC then keeps the types from
2689 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002690 //
2691 // If a variadic prototype is followed by a non-variadic K&R definition,
2692 // the K&R definition becomes variadic. This is sort of an edge case, but
2693 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2694 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002695 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002696 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002697 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002698 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002699 SmallVector<QualType, 16> ArgTypes;
2700 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002701 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002702 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002703 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002704 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002705
Douglas Gregora74a2972009-03-06 22:43:54 +00002706 // Determine whether this is the GNU C extension.
Alp Toker314cc812014-01-25 16:55:45 +00002707 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2708 NewProto->getReturnType());
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002709 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002710 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002711 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002712 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2713 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002714 if (Context.typesAreCompatible(OldParm->getType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00002715 NewProto->getParamType(Idx))) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002716 ArgTypes.push_back(NewParm->getType());
2717 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002718 NewParm->getType(),
2719 /*CompareUnqualified=*/true)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002720 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2721 NewProto->getParamType(Idx) };
Douglas Gregora74a2972009-03-06 22:43:54 +00002722 Warnings.push_back(Warn);
2723 ArgTypes.push_back(NewParm->getType());
2724 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002725 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002726 }
2727
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002728 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002729 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2730 Diag(Warnings[Warn].NewParm->getLocation(),
2731 diag::ext_param_promoted_not_compatible_with_prototype)
2732 << Warnings[Warn].PromotedType
2733 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002734 if (Warnings[Warn].OldParm->getLocation().isValid())
2735 Diag(Warnings[Warn].OldParm->getLocation(),
2736 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002737 }
2738
Richard Smith1c34fb72013-08-13 18:18:50 +00002739 if (MergeTypeWithOld)
2740 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2741 OldProto->getExtProtoInfo()));
2742 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002743 }
2744
2745 // Fall through to diagnose conflicting types.
2746 }
2747
John McCallad327cd2013-04-14 08:50:55 +00002748 // A function that has already been declared has been redeclared or
2749 // defined with a different type; show an appropriate diagnostic.
2750
2751 // If the previous declaration was an implicitly-generated builtin
2752 // declaration, then at the very least we should use a specialized note.
2753 unsigned BuiltinID;
2754 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2755 // If it's actually a library-defined builtin function like 'malloc'
2756 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002757 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002758 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002759 Diag(OldLocation, diag::note_previous_builtin_declaration)
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002760 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002761
2762 // If this is a global redeclaration, just forget hereafter
2763 // about the "builtin-ness" of the function.
2764 //
2765 // Doing this for local extern declarations is problematic. If
2766 // the builtin declaration remains visible, a second invalid
2767 // local declaration will produce a hard error; if it doesn't
2768 // remain visible, a single bogus local redeclaration (which is
2769 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002770 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002771 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2772
Douglas Gregor893c2c92009-03-23 17:47:24 +00002773 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002774 }
Steve Naroff17832a42008-01-16 15:01:34 +00002775
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002776 PrevDiag = diag::note_previous_builtin_declaration;
2777 }
2778
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002779 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Richard Smithbdd14642014-02-04 01:14:30 +00002780 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002781 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002782}
2783
Douglas Gregore62c0a42009-02-24 01:23:02 +00002784/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002785/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002786///
2787/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002788/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002789/// the new declaration, once we know that New is in fact a
2790/// redeclaration of Old.
2791///
2792/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002793bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002794 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002795 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002796 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002797
Douglas Gregore62c0a42009-02-24 01:23:02 +00002798 // Merge "pure" flag.
2799 if (Old->isPure())
2800 New->setPure();
2801
Rafael Espindolabefe1302012-11-25 14:07:59 +00002802 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002803 if (Old->getMostRecentDecl()->isUsed(false))
2804 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002805
John McCallf79e87d2011-03-02 04:00:57 +00002806 // Merge attributes from the parameters. These can mismatch with K&R
2807 // declarations.
2808 if (New->getNumParams() == Old->getNumParams())
2809 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2810 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002811 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002812
David Blaikiebbafb8a2012-03-11 07:00:24 +00002813 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002814 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002815
Rafael Espindola8778c282012-11-29 16:09:03 +00002816 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002817 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2818 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002819 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002820 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002821 New->setType(Merged);
2822
Douglas Gregore62c0a42009-02-24 01:23:02 +00002823 return false;
2824}
2825
John McCall31168b02011-06-15 23:02:42 +00002826
John McCallf79e87d2011-03-02 04:00:57 +00002827void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002828 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002829
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002830 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002831 AvailabilityMergeKind MergeKind =
2832 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2833 : AMK_Override;
2834 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002835
2836 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002837 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2838 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002839 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002840 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002841 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002842 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002843
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002844 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002845}
2846
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002847/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2848/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002849/// emitting diagnostics as appropriate.
2850///
2851/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002852/// to here in AddInitializerToDecl. We can't check them before the initializer
2853/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002854void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2855 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002856 if (New->isInvalidDecl() || Old->isInvalidDecl())
2857 return;
2858
2859 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002860 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002861 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002862 // We don't know what the new type is until the initializer is attached.
2863 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002864 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2865 // These could still be something that needs exception specs checked.
2866 return MergeVarDeclExceptionSpecs(New, Old);
2867 }
Richard Smith30482bc2011-02-20 03:19:35 +00002868 // C++ [basic.link]p10:
2869 // [...] the types specified by all declarations referring to a given
2870 // object or function shall be identical, except that declarations for an
2871 // array object can specify array types that differ by the presence or
2872 // absence of a major array bound (8.3.4).
2873 else if (Old->getType()->isIncompleteArrayType() &&
2874 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002875 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2876 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2877 if (Context.hasSameType(OldArray->getElementType(),
2878 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002879 MergedT = New->getType();
2880 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002881 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002882 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2883 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2884 if (Context.hasSameType(OldArray->getElementType(),
2885 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002886 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002887 } else if (New->getType()->isObjCObjectPointerType() &&
2888 Old->getType()->isObjCObjectPointerType()) {
2889 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2890 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002891 }
2892 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002893 // C 6.2.7p2:
2894 // All declarations that refer to the same object or function shall have
2895 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002896 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2897 }
2898 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002899 // It's OK if we couldn't merge types if either type is dependent, for a
2900 // block-scope variable. In other cases (static data members of class
2901 // templates, variable templates, ...), we require the types to be
2902 // equivalent.
2903 // FIXME: The C++ standard doesn't say anything about this.
2904 if ((New->getType()->isDependentType() ||
2905 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2906 // If the old type was dependent, we can't merge with it, so the new type
2907 // becomes dependent for now. We'll reproduce the original type when we
2908 // instantiate the TypeSourceInfo for the variable.
2909 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2910 New->setType(Context.DependentTy);
2911 return;
2912 }
2913
2914 // FIXME: Even if this merging succeeds, some other non-visible declaration
2915 // of this variable might have an incompatible type. For instance:
2916 //
2917 // extern int arr[];
2918 // void f() { extern int arr[2]; }
2919 // void g() { extern int arr[3]; }
2920 //
2921 // Neither C nor C++ requires a diagnostic for this, but we should still try
2922 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002923 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002924 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002925 Diag(Old->getLocation(), diag::note_previous_definition);
2926 return New->setInvalidDecl();
2927 }
John McCallb65e8fe2013-04-01 18:34:28 +00002928
2929 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002930 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002931 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002932 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002933}
2934
Richard Smith3c785782013-09-03 21:00:58 +00002935static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2936 LookupResult &Previous) {
2937 // C11 6.2.7p4:
2938 // For an identifier with internal or external linkage declared
2939 // in a scope in which a prior declaration of that identifier is
2940 // visible, if the prior declaration specifies internal or
2941 // external linkage, the type of the identifier at the later
2942 // declaration becomes the composite type.
2943 //
2944 // If the variable isn't visible, we do not merge with its type.
2945 if (Previous.isShadowed())
2946 return false;
2947
2948 if (S.getLangOpts().CPlusPlus) {
2949 // C++11 [dcl.array]p3:
2950 // If there is a preceding declaration of the entity in the same
2951 // scope in which the bound was specified, an omitted array bound
2952 // is taken to be the same as in that earlier declaration.
2953 return NewVD->isPreviousDeclInSameBlockScope() ||
2954 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2955 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2956 } else {
2957 // If the old declaration was function-local, don't merge with its
2958 // type unless we're in the same function.
2959 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2960 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2961 }
2962}
2963
Chris Lattner01564d92007-01-27 19:27:06 +00002964/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2965/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2966/// situation, merging decls or emitting diagnostics as appropriate.
2967///
Mike Stump11289f42009-09-09 15:08:12 +00002968/// Tentative definition rules (C99 6.9.2p2) are checked by
2969/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002970/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002971///
Richard Smith3c785782013-09-03 21:00:58 +00002972void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00002973 // If the new decl is already invalid, don't do any other checking.
2974 if (New->isInvalidDecl())
2975 return;
Mike Stump11289f42009-09-09 15:08:12 +00002976
Richard Smithbeef3452014-01-16 23:39:20 +00002977 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2978
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002979 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00002980 VarDecl *Old = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00002981 VarTemplateDecl *OldTemplate = 0;
2982 if (Previous.isSingleResult()) {
2983 if (NewTemplate) {
2984 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2985 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
2986 } else
2987 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002988 }
2989 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002990 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002991 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002992 Diag(Previous.getRepresentativeDecl()->getLocation(),
2993 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002994 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002995 }
Chris Lattner84966392008-03-03 03:28:21 +00002996
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00002997 if (!shouldLinkPossiblyHiddenDecl(Old, New))
2998 return;
2999
Richard Smithbeef3452014-01-16 23:39:20 +00003000 // Ensure the template parameters are compatible.
3001 if (NewTemplate &&
3002 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3003 OldTemplate->getTemplateParameters(),
3004 /*Complain=*/true, TPL_TemplateMatch))
3005 return;
3006
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003007 // C++ [class.mem]p1:
3008 // A member shall not be declared twice in the member-specification [...]
3009 //
3010 // Here, we need only consider static data members.
3011 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3012 Diag(New->getLocation(), diag::err_duplicate_member)
3013 << New->getIdentifier();
3014 Diag(Old->getLocation(), diag::note_previous_declaration);
3015 New->setInvalidDecl();
3016 }
3017
Douglas Gregor32c17572012-01-01 20:30:41 +00003018 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003019 // Warn if an already-declared variable is made a weak_import in a subsequent
3020 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003021 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003022 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003023 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003024 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3025 Diag(Old->getLocation(), diag::note_previous_definition);
3026 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003027 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003028 }
Chris Lattner84966392008-03-03 03:28:21 +00003029
Richard Smith30482bc2011-02-20 03:19:35 +00003030 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003031 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3032
Richard Smith30482bc2011-02-20 03:19:35 +00003033 if (New->isInvalidDecl())
3034 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003035
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003036 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003037 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003038 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003039 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003040 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003041 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003042 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003043 }
Mike Stump11289f42009-09-09 15:08:12 +00003044 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003045 // For an identifier declared with the storage-class specifier
3046 // extern in a scope in which a prior declaration of that
3047 // identifier is visible,23) if the prior declaration specifies
3048 // internal or external linkage, the linkage of the identifier at
3049 // the later declaration is the same as the linkage specified at
3050 // the prior declaration. If no prior declaration is visible, or
3051 // if the prior declaration specifies no linkage, then the
3052 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003053 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003054 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003055 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003056 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003057 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003058 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003059 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003060 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003061 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003062
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003063 // Check if extern is followed by non-extern and vice-versa.
3064 if (New->hasExternalStorage() &&
3065 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3066 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3067 Diag(Old->getLocation(), diag::note_previous_definition);
3068 return New->setInvalidDecl();
3069 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003070 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3071 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003072 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3073 Diag(Old->getLocation(), diag::note_previous_definition);
3074 return New->setInvalidDecl();
3075 }
3076
Steve Naroffa5629372008-09-17 14:05:40 +00003077 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003078
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003079 // FIXME: The test for external storage here seems wrong? We still
3080 // need to check for mismatches.
3081 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003082 // Don't complain about out-of-line definitions of static members.
3083 !(Old->getLexicalDeclContext()->isRecord() &&
3084 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003085 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003086 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003087 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003088 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003089
Richard Smithfd3834f2013-04-13 02:43:54 +00003090 if (New->getTLSKind() != Old->getTLSKind()) {
3091 if (!Old->getTLSKind()) {
3092 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3093 Diag(Old->getLocation(), diag::note_previous_declaration);
3094 } else if (!New->getTLSKind()) {
3095 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3096 Diag(Old->getLocation(), diag::note_previous_declaration);
3097 } else {
3098 // Do not allow redeclaration to change the variable between requiring
3099 // static and dynamic initialization.
3100 // FIXME: GCC allows this, but uses the TLS keyword on the first
3101 // declaration to determine the kind. Do we need to be compatible here?
3102 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3103 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3104 Diag(Old->getLocation(), diag::note_previous_declaration);
3105 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003106 }
3107
Sebastian Redlf1842912010-02-02 18:35:11 +00003108 // C++ doesn't have tentative definitions, so go right ahead and check here.
3109 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003110 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003111 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003112 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003113 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003114 Diag(Def->getLocation(), diag::note_previous_definition);
3115 New->setInvalidDecl();
3116 return;
3117 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003118
Rafael Espindolaf4187652013-02-14 01:18:37 +00003119 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003120 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3121 Diag(Old->getLocation(), diag::note_previous_definition);
3122 New->setInvalidDecl();
3123 return;
3124 }
3125
Rafael Espindolabefe1302012-11-25 14:07:59 +00003126 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003127 if (Old->getMostRecentDecl()->isUsed(false))
3128 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003129
Douglas Gregor0760fa12009-03-10 23:43:53 +00003130 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003131 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003132 if (NewTemplate)
3133 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003134
3135 // Inherit access appropriately.
3136 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003137 if (NewTemplate)
3138 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003139}
3140
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003141/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3142/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003143Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003144 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003145 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003146}
3147
David Majnemer2206bf52014-03-05 08:57:59 +00003148static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003149 if (!S.Context.getLangOpts().CPlusPlus)
3150 return;
3151
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003152 if (isa<CXXRecordDecl>(Tag->getParent())) {
3153 // If this tag is the direct child of a class, number it if
3154 // it is anonymous.
3155 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3156 return;
3157 MangleNumberingContext &MCtx =
3158 S.Context.getManglingNumberContext(Tag->getParent());
David Majnemerf27217f2014-03-05 18:55:38 +00003159 S.Context.setManglingNumber(
3160 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003161 return;
3162 }
3163
3164 // If this tag isn't a direct child of a class, number it if it is local.
3165 Decl *ManglingContextDecl;
3166 if (MangleNumberingContext *MCtx =
3167 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3168 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003169 S.Context.setManglingNumber(
3170 Tag,
3171 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003172 }
3173}
3174
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003175/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003176/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003177/// parameters to cope with template friend declarations.
3178Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3179 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003180 MultiTemplateParamsArg TemplateParams,
3181 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003182 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003183 TagDecl *Tag = 0;
3184 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3185 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003186 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003187 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003188 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003189 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003190
3191 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003192 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003193
John McCall07e91c02009-08-06 02:15:43 +00003194 // Note that the above type specs guarantee that the
3195 // type rep is a Decl, whereas in many of the others
3196 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003197 if (isa<TagDecl>(TagD))
3198 Tag = cast<TagDecl>(TagD);
3199 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3200 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003201 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003202
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003203 if (Tag) {
David Majnemer2206bf52014-03-05 08:57:59 +00003204 HandleTagNumbering(*this, Tag, S);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003205 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003206 if (Tag->isInvalidDecl())
3207 return Tag;
3208 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003209
Nuno Lopese9823fa2009-12-17 11:35:26 +00003210 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3211 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3212 // or incomplete types shall not be restrict-qualified."
3213 if (TypeQuals & DeclSpec::TQ_restrict)
3214 Diag(DS.getRestrictSpecLoc(),
3215 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3216 << DS.getSourceRange();
3217 }
3218
Richard Smitha77a0a62011-08-15 21:04:07 +00003219 if (DS.isConstexprSpecified()) {
3220 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3221 // and definitions of functions and variables.
3222 if (Tag)
3223 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3224 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3225 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003226 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3227 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003228 else
3229 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3230 // Don't emit warnings after this error.
3231 return TagD;
3232 }
3233
Richard Smithb1402ae2013-03-18 22:52:47 +00003234 DiagnoseFunctionSpecifiers(DS);
3235
Douglas Gregor3dad8422009-09-26 06:47:28 +00003236 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003237 // If we're dealing with a decl but not a TagDecl, assume that
3238 // whatever routines created it handled the friendship aspect.
3239 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003240 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003241 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003242 }
John McCallaa017372011-03-22 23:00:04 +00003243
Richard Smithb1402ae2013-03-18 22:52:47 +00003244 CXXScopeSpec &SS = DS.getTypeSpecScope();
3245 bool IsExplicitSpecialization =
3246 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3247 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3248 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3249 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3250 // nested-name-specifier unless it is an explicit instantiation
3251 // or an explicit specialization.
3252 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3253 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3254 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3255 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3256 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3257 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3258 << SS.getRange();
3259 return 0;
3260 }
3261
3262 // Track whether this decl-specifier declares anything.
3263 bool DeclaresAnything = true;
3264
3265 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003266 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003267 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003268 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003269 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003270 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003271 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003272
Richard Smithb1402ae2013-03-18 22:52:47 +00003273 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003274 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003275 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003276
Richard Smithb1402ae2013-03-18 22:52:47 +00003277 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003278 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003279 CurContext->isRecord() &&
3280 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3281 // Handle 2 kinds of anonymous struct:
3282 // struct STRUCT;
3283 // and
3284 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3285 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003286 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003287 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3288 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003289 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003290 << DS.getSourceRange();
3291 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3292 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003293 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003294
3295 // Skip all the checks below if we have a type error.
3296 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3297 (TagD && TagD->isInvalidDecl()))
3298 return TagD;
3299
3300 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003301 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3302 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3303 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003304 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3305 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003306
John McCallaa017372011-03-22 23:00:04 +00003307 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003308 // Customize diagnostic for a typedef missing a name.
3309 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003310 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003311 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003312 else
3313 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003314 }
Mike Stump11289f42009-09-09 15:08:12 +00003315
Richard Smithb1402ae2013-03-18 22:52:47 +00003316 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003317 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3318 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3319 << Tag->getTagKind()
3320 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3321
Richard Smithb1402ae2013-03-18 22:52:47 +00003322 ActOnDocumentableDecl(TagD);
3323
3324 // C 6.7/2:
3325 // A declaration [...] shall declare at least a declarator [...], a tag,
3326 // or the members of an enumeration.
3327 // C++ [dcl.dcl]p3:
3328 // [If there are no declarators], and except for the declaration of an
3329 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3330 // names into the program, or shall redeclare a name introduced by a
3331 // previous declaration.
3332 if (!DeclaresAnything) {
3333 // In C, we allow this as a (popular) extension / bug. Don't bother
3334 // producing further diagnostics for redundant qualifiers after this.
3335 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3336 return TagD;
3337 }
3338
3339 // C++ [dcl.stc]p1:
3340 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3341 // init-declarator-list of the declaration shall not be empty.
3342 // C++ [dcl.fct.spec]p1:
3343 // If a cv-qualifier appears in a decl-specifier-seq, the
3344 // init-declarator-list of the declaration shall not be empty.
3345 //
3346 // Spurious qualifiers here appear to be valid in C.
3347 unsigned DiagID = diag::warn_standalone_specifier;
3348 if (getLangOpts().CPlusPlus)
3349 DiagID = diag::ext_standalone_specifier;
3350
3351 // Note that a linkage-specification sets a storage class, but
3352 // 'extern "C" struct foo;' is actually valid and not theoretically
3353 // useless.
3354 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3355 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3356 Diag(DS.getStorageClassSpecLoc(), DiagID)
3357 << DeclSpec::getSpecifierName(SCS);
3358
Richard Smithb4a9e862013-04-12 22:46:28 +00003359 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3360 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3361 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003362 if (DS.getTypeQualifiers()) {
3363 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3364 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3365 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3366 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3367 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003368 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3369 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003370 }
3371
Eli Friedmane3217952011-12-17 00:36:09 +00003372 // Warn about ignored type attributes, for example:
3373 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003374 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003375 if (!DS.getAttributes().empty()) {
3376 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3377 if (TypeSpecType == DeclSpec::TST_class ||
3378 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003379 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003380 TypeSpecType == DeclSpec::TST_union ||
3381 TypeSpecType == DeclSpec::TST_enum) {
3382 AttributeList* attrs = DS.getAttributes().getList();
3383 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003384 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003385 << attrs->getName()
3386 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3387 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003388 TypeSpecType == DeclSpec::TST_union ? 2 :
3389 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003390 attrs = attrs->getNext();
3391 }
3392 }
3393 }
John McCallaa017372011-03-22 23:00:04 +00003394
John McCall48871652010-08-21 09:40:31 +00003395 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003396}
3397
John McCallea305ed2009-12-18 10:40:03 +00003398/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003399/// check if there's an existing declaration that can't be overloaded.
3400///
3401/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003402static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3403 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003404 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003405 DeclarationName Name,
3406 SourceLocation NameLoc,
3407 unsigned diagnostic) {
3408 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3409 Sema::ForRedeclaration);
3410 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003411
John McCallea305ed2009-12-18 10:40:03 +00003412 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003413 return false;
3414
3415 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003416 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003417 assert(PrevDecl && "Expected a non-null Decl");
3418
3419 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3420 return false;
John McCall1f82f242009-11-18 22:49:29 +00003421
John McCallea305ed2009-12-18 10:40:03 +00003422 SemaRef.Diag(NameLoc, diagnostic) << Name;
3423 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003424
3425 return true;
3426}
3427
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003428/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3429/// anonymous struct or union AnonRecord into the owning context Owner
3430/// and scope S. This routine will be invoked just after we realize
3431/// that an unnamed union or struct is actually an anonymous union or
3432/// struct, e.g.,
3433///
3434/// @code
3435/// union {
3436/// int i;
3437/// float f;
3438/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3439/// // f into the surrounding scope.x
3440/// @endcode
3441///
3442/// This routine is recursive, injecting the names of nested anonymous
3443/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003444static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003445 DeclContext *Owner,
3446 RecordDecl *AnonRecord,
3447 AccessSpecifier AS,
3448 SmallVectorImpl<NamedDecl *> &Chaining,
3449 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003450 unsigned diagKind
3451 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3452 : diag::err_anonymous_struct_member_redecl;
3453
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003454 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003455
3456 // Look every FieldDecl and IndirectFieldDecl with a name.
Aaron Ballman629afae2014-03-07 19:56:05 +00003457 for (auto *D : AnonRecord->decls()) {
3458 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3459 cast<NamedDecl>(D)->getDeclName()) {
3460 ValueDecl *VD = cast<ValueDecl>(D);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003461 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3462 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003463 // C++ [class.union]p2:
3464 // The names of the members of an anonymous union shall be
3465 // distinct from the names of any other entity in the
3466 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003467 Invalid = true;
3468 } else {
3469 // C++ [class.union]p2:
3470 // For the purpose of name lookup, after the anonymous union
3471 // definition, the members of the anonymous union are
3472 // considered to have been defined in the scope in which the
3473 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003474 unsigned OldChainingSize = Chaining.size();
3475 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
Aaron Ballman29c94602014-03-07 18:36:15 +00003476 for (auto *PI : IF->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00003477 Chaining.push_back(PI);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003478 else
3479 Chaining.push_back(VD);
3480
Francois Pichet783dd6e2010-11-21 06:08:52 +00003481 assert(Chaining.size() >= 2);
3482 NamedDecl **NamedChain =
3483 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3484 for (unsigned i = 0; i < Chaining.size(); i++)
3485 NamedChain[i] = Chaining[i];
3486
3487 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003488 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3489 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003490 NamedChain, Chaining.size());
3491
3492 IndirectField->setAccess(AS);
3493 IndirectField->setImplicit();
3494 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003495
3496 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003497 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003498
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003499 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003500 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003501 }
3502 }
3503
3504 return Invalid;
3505}
3506
Douglas Gregorc4df4072010-04-19 22:54:31 +00003507/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3508/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003509/// illegal input values are mapped to SC_None.
3510static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003511StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3512 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3513 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3514 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003515 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003516 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003517 case DeclSpec::SCS_extern:
3518 if (DS.isExternInLinkageSpec())
3519 return SC_None;
3520 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003521 case DeclSpec::SCS_static: return SC_Static;
3522 case DeclSpec::SCS_auto: return SC_Auto;
3523 case DeclSpec::SCS_register: return SC_Register;
3524 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003525 // Illegal SCSs map to None: error reporting is up to the caller.
3526 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003527 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003528 }
3529 llvm_unreachable("unknown storage class specifier");
3530}
3531
Richard Smithab44d5b2013-12-10 08:25:00 +00003532static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3533 assert(Record->hasInClassInitializer());
3534
Aaron Ballman629afae2014-03-07 19:56:05 +00003535 for (const auto *I : Record->decls()) {
3536 const auto *FD = dyn_cast<FieldDecl>(I);
3537 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Richard Smithab44d5b2013-12-10 08:25:00 +00003538 FD = IFD->getAnonField();
3539 if (FD && FD->hasInClassInitializer())
3540 return FD->getLocation();
3541 }
3542
3543 llvm_unreachable("couldn't find in-class initializer");
3544}
3545
3546static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3547 SourceLocation DefaultInitLoc) {
3548 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3549 return;
3550
3551 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3552 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3553}
3554
3555static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3556 CXXRecordDecl *AnonUnion) {
3557 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3558 return;
3559
3560 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3561}
3562
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003563/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003564/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003565/// (C++ [class.union]) and a C11 feature; anonymous structures
3566/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003567Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003568 AccessSpecifier AS,
3569 RecordDecl *Record,
3570 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003571 DeclContext *Owner = Record->getDeclContext();
3572
3573 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003574 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003575 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003576 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003577 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003578 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003579 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003580
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003581 // C and C++ require different kinds of checks for anonymous
3582 // structs/unions.
3583 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003584 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003585 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003586 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003587 if (Record->isUnion()) {
3588 // C++ [class.union]p6:
3589 // Anonymous unions declared in a named namespace or in the
3590 // global namespace shall be declared static.
3591 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3592 (isa<TranslationUnitDecl>(Owner) ||
3593 (isa<NamespaceDecl>(Owner) &&
3594 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003595 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3596 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003597
3598 // Recover by adding 'static'.
3599 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003600 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003601 }
3602 // C++ [class.union]p6:
3603 // A storage class is not allowed in a declaration of an
3604 // anonymous union in a class scope.
3605 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3606 isa<RecordDecl>(Owner)) {
3607 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003608 diag::err_anonymous_union_with_storage_spec)
3609 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003610
3611 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003612 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3613 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003614 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003615 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003616 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003617
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003618 // Ignore const/volatile/restrict qualifiers.
3619 if (DS.getTypeQualifiers()) {
3620 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3621 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003622 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003623 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3624 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003625 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003626 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003627 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003628 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3629 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003630 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003631 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003632 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003633 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003634 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3635 Diag(DS.getAtomicSpecLoc(),
3636 diag::ext_anonymous_struct_union_qualified)
3637 << Record->isUnion() << "_Atomic"
3638 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003639
3640 DS.ClearTypeQualifiers();
3641 }
3642
Mike Stump11289f42009-09-09 15:08:12 +00003643 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003644 // The member-specification of an anonymous union shall only
3645 // define non-static data members. [Note: nested types and
3646 // functions cannot be declared within an anonymous union. ]
Aaron Ballman629afae2014-03-07 19:56:05 +00003647 for (auto *Mem : Record->decls()) {
3648 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003649 // C++ [class.union]p3:
3650 // An anonymous union shall not have private or protected
3651 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003652 assert(FD->getAccess() != AS_none);
3653 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003654 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3655 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3656 Invalid = true;
3657 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003658
Alexis Hunt97ab5542011-05-16 22:41:40 +00003659 // C++ [class.union]p1
3660 // An object of a class with a non-trivial constructor, a non-trivial
3661 // copy constructor, a non-trivial destructor, or a non-trivial copy
3662 // assignment operator cannot be a member of a union, nor can an
3663 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003664 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003665 Invalid = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00003666 } else if (Mem->isImplicit()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003667 // Any implicit members are fine.
Aaron Ballman629afae2014-03-07 19:56:05 +00003668 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
Douglas Gregor8761da52009-02-03 00:34:39 +00003669 // This is a type that showed up in an
3670 // elaborated-type-specifier inside the anonymous struct or
3671 // union, but which actually declares a type outside of the
3672 // anonymous struct or union. It's okay.
Aaron Ballman629afae2014-03-07 19:56:05 +00003673 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003674 if (!MemRecord->isAnonymousStructOrUnion() &&
3675 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003676 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003677 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003678 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3679 << (int)Record->isUnion();
3680 else {
3681 // This is a nested type declaration.
3682 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3683 << (int)Record->isUnion();
3684 Invalid = true;
3685 }
Richard Smith254d2662013-01-28 00:54:05 +00003686 } else {
3687 // This is an anonymous type definition within another anonymous type.
3688 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3689 // not part of standard C++.
3690 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003691 diag::ext_anonymous_record_with_anonymous_type)
3692 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003693 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003694 } else if (isa<AccessSpecDecl>(Mem)) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00003695 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003696 } else {
3697 // We have something that isn't a non-static data
3698 // member. Complain about it.
3699 unsigned DK = diag::err_anonymous_record_bad_member;
Aaron Ballman629afae2014-03-07 19:56:05 +00003700 if (isa<TypeDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003701 DK = diag::err_anonymous_record_with_type;
Aaron Ballman629afae2014-03-07 19:56:05 +00003702 else if (isa<FunctionDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003703 DK = diag::err_anonymous_record_with_function;
Aaron Ballman629afae2014-03-07 19:56:05 +00003704 else if (isa<VarDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003705 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003706
3707 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003708 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003709 DK == diag::err_anonymous_record_with_type)
Aaron Ballman629afae2014-03-07 19:56:05 +00003710 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003711 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003712 else {
Aaron Ballman629afae2014-03-07 19:56:05 +00003713 Diag(Mem->getLocation(), DK)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003714 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003715 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003716 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003717 }
3718 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003719
3720 // C++11 [class.union]p8 (DR1460):
3721 // At most one variant member of a union may have a
3722 // brace-or-equal-initializer.
3723 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3724 Owner->isRecord())
3725 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3726 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003727 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003728
3729 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003730 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003731 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003732 Invalid = true;
3733 }
3734
John McCallfa2d6922009-10-22 23:31:08 +00003735 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003736 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003737 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003738 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003739
Mike Stump11289f42009-09-09 15:08:12 +00003740 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003741 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003742 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003743 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003744 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003745 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003746 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003747 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003748 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003749 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003750 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003751 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003752 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003753 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003754 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003755 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003756 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003757 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003758 // mutable can only appear on non-static class members, so it's always
3759 // an error here
3760 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3761 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003762 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003763 }
3764
Abramo Bagnaradff19302011-03-08 08:55:46 +00003765 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003766 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003767 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003768 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003769 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003770
3771 // Default-initialize the implicit variable. This initialization will be
3772 // trivial in almost all cases, except if a union member has an in-class
3773 // initializer:
3774 // union { int n = 0; };
3775 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003776 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003777 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003778
Richard Smithab44d5b2013-12-10 08:25:00 +00003779 // Mark this as an anonymous struct/union type.
3780 Record->setAnonymousStructOrUnion(true);
3781
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003782 // Add the anonymous struct/union object to the current
3783 // context. We'll be referencing this object when we refer to one of
3784 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003785 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003786
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003787 // Inject the members of the anonymous struct/union into the owning
3788 // context and into the identifier resolver chain for name lookup
3789 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003790 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003791 Chain.push_back(Anon);
3792
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003793 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3794 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003795 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003796
David Majnemer2206bf52014-03-05 08:57:59 +00003797 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
3798 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
3799 Decl *ManglingContextDecl;
3800 if (MangleNumberingContext *MCtx =
3801 getCurrentMangleNumberContext(NewVD->getDeclContext(),
3802 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003803 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00003804 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
3805 }
3806 }
3807 }
3808
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003809 if (Invalid)
3810 Anon->setInvalidDecl();
3811
John McCall48871652010-08-21 09:40:31 +00003812 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003813}
3814
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003815/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3816/// Microsoft C anonymous structure.
3817/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3818/// Example:
3819///
3820/// struct A { int a; };
3821/// struct B { struct A; int b; };
3822///
3823/// void foo() {
3824/// B var;
3825/// var.a = 3;
3826/// }
3827///
3828Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3829 RecordDecl *Record) {
3830
3831 // If there is no Record, get the record via the typedef.
3832 if (!Record)
3833 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3834
3835 // Mock up a declarator.
3836 Declarator Dc(DS, Declarator::TypeNameContext);
3837 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3838 assert(TInfo && "couldn't build declarator info for anonymous struct");
3839
3840 // Create a declaration for this anonymous struct.
3841 NamedDecl* Anon = FieldDecl::Create(Context,
3842 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003843 DS.getLocStart(),
3844 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003845 /*IdentifierInfo=*/0,
3846 Context.getTypeDeclType(Record),
3847 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003848 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003849 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003850 Anon->setImplicit();
3851
3852 // Add the anonymous struct object to the current context.
3853 CurContext->addDecl(Anon);
3854
3855 // Inject the members of the anonymous struct into the current
3856 // context and into the identifier resolver chain for name lookup
3857 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003858 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003859 Chain.push_back(Anon);
3860
Nico Weberf8bb3de2012-02-01 00:41:00 +00003861 RecordDecl *RecordDef = Record->getDefinition();
3862 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3863 RecordDef, AS_none,
3864 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003865 Anon->setInvalidDecl();
3866
3867 return Anon;
3868}
Steve Naroff2fea1392007-09-02 02:04:30 +00003869
Douglas Gregor92751d42008-11-17 22:58:34 +00003870/// GetNameForDeclarator - Determine the full declaration name for the
3871/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003872DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003873 return GetNameFromUnqualifiedId(D.getName());
3874}
3875
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003876/// \brief Retrieves the declaration name from a parsed unqualified-id.
3877DeclarationNameInfo
3878Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3879 DeclarationNameInfo NameInfo;
3880 NameInfo.setLoc(Name.StartLocation);
3881
Douglas Gregor7861a802009-11-03 01:35:08 +00003882 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003883
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003884 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003885 case UnqualifiedId::IK_Identifier:
3886 NameInfo.setName(Name.Identifier);
3887 NameInfo.setLoc(Name.StartLocation);
3888 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003889
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003890 case UnqualifiedId::IK_OperatorFunctionId:
3891 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3892 Name.OperatorFunctionId.Operator));
3893 NameInfo.setLoc(Name.StartLocation);
3894 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3895 = Name.OperatorFunctionId.SymbolLocations[0];
3896 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3897 = Name.EndLocation.getRawEncoding();
3898 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003899
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003900 case UnqualifiedId::IK_LiteralOperatorId:
3901 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3902 Name.Identifier));
3903 NameInfo.setLoc(Name.StartLocation);
3904 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3905 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003906
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003907 case UnqualifiedId::IK_ConversionFunctionId: {
3908 TypeSourceInfo *TInfo;
3909 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3910 if (Ty.isNull())
3911 return DeclarationNameInfo();
3912 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3913 Context.getCanonicalType(Ty)));
3914 NameInfo.setLoc(Name.StartLocation);
3915 NameInfo.setNamedTypeInfo(TInfo);
3916 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003917 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003918
3919 case UnqualifiedId::IK_ConstructorName: {
3920 TypeSourceInfo *TInfo;
3921 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3922 if (Ty.isNull())
3923 return DeclarationNameInfo();
3924 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3925 Context.getCanonicalType(Ty)));
3926 NameInfo.setLoc(Name.StartLocation);
3927 NameInfo.setNamedTypeInfo(TInfo);
3928 return NameInfo;
3929 }
3930
3931 case UnqualifiedId::IK_ConstructorTemplateId: {
3932 // In well-formed code, we can only have a constructor
3933 // template-id that refers to the current context, so go there
3934 // to find the actual type being constructed.
3935 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3936 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3937 return DeclarationNameInfo();
3938
3939 // Determine the type of the class being constructed.
3940 QualType CurClassType = Context.getTypeDeclType(CurClass);
3941
3942 // FIXME: Check two things: that the template-id names the same type as
3943 // CurClassType, and that the template-id does not occur when the name
3944 // was qualified.
3945
3946 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3947 Context.getCanonicalType(CurClassType)));
3948 NameInfo.setLoc(Name.StartLocation);
3949 // FIXME: should we retrieve TypeSourceInfo?
3950 NameInfo.setNamedTypeInfo(0);
3951 return NameInfo;
3952 }
3953
3954 case UnqualifiedId::IK_DestructorName: {
3955 TypeSourceInfo *TInfo;
3956 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3957 if (Ty.isNull())
3958 return DeclarationNameInfo();
3959 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3960 Context.getCanonicalType(Ty)));
3961 NameInfo.setLoc(Name.StartLocation);
3962 NameInfo.setNamedTypeInfo(TInfo);
3963 return NameInfo;
3964 }
3965
3966 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003967 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003968 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3969 return Context.getNameForTemplate(TName, TNameLoc);
3970 }
3971
3972 } // switch (Name.getKind())
3973
David Blaikie83d382b2011-09-23 05:06:16 +00003974 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003975}
3976
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003977static QualType getCoreType(QualType Ty) {
3978 do {
3979 if (Ty->isPointerType() || Ty->isReferenceType())
3980 Ty = Ty->getPointeeType();
3981 else if (Ty->isArrayType())
3982 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3983 else
3984 return Ty.withoutLocalFastQualifiers();
3985 } while (true);
3986}
3987
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003988/// hasSimilarParameters - Determine whether the C++ functions Declaration
3989/// and Definition have "nearly" matching parameters. This heuristic is
3990/// used to improve diagnostics in the case where an out-of-line function
3991/// definition doesn't match any declaration within the class or namespace.
3992/// Also sets Params to the list of indices to the parameters that differ
3993/// between the declaration and the definition. If hasSimilarParameters
3994/// returns true and Params is empty, then all of the parameters match.
3995static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003996 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003997 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003998 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003999 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00004000 if (Declaration->param_size() != Definition->param_size())
4001 return false;
4002 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4003 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4004 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4005
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004006 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00004007 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004008 continue;
4009
4010 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4011 QualType DefParamBaseTy = getCoreType(DefParamTy);
4012 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4013 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4014
4015 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4016 (DeclTyName && DeclTyName == DefTyName))
4017 Params.push_back(Idx);
4018 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004019 return false;
4020 }
4021
4022 return true;
4023}
4024
John McCall99b2fe52010-04-29 23:50:39 +00004025/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4026/// declarator needs to be rebuilt in the current instantiation.
4027/// Any bits of declarator which appear before the name are valid for
4028/// consideration here. That's specifically the type in the decl spec
4029/// and the base type in any member-pointer chunks.
4030static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4031 DeclarationName Name) {
4032 // The types we specifically need to rebuild are:
4033 // - typenames, typeofs, and decltypes
4034 // - types which will become injected class names
4035 // Of course, we also need to rebuild any type referencing such a
4036 // type. It's safest to just say "dependent", but we call out a
4037 // few cases here.
4038
4039 DeclSpec &DS = D.getMutableDeclSpec();
4040 switch (DS.getTypeSpecType()) {
4041 case DeclSpec::TST_typename:
4042 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004043 case DeclSpec::TST_underlyingType:
4044 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004045 // Grab the type from the parser.
4046 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004047 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004048 if (T.isNull() || !T->isDependentType()) break;
4049
4050 // Make sure there's a type source info. This isn't really much
4051 // of a waste; most dependent types should have type source info
4052 // attached already.
4053 if (!TSI)
4054 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4055
4056 // Rebuild the type in the current instantiation.
4057 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4058 if (!TSI) return true;
4059
4060 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004061 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4062 DS.UpdateTypeRep(LocType);
4063 break;
4064 }
4065
Richard Smith1620ebd2012-10-01 20:35:07 +00004066 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004067 case DeclSpec::TST_typeofExpr: {
4068 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004069 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004070 if (Result.isInvalid()) return true;
4071 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004072 break;
4073 }
4074
4075 default:
4076 // Nothing to do for these decl specs.
4077 break;
4078 }
4079
4080 // It doesn't matter what order we do this in.
4081 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4082 DeclaratorChunk &Chunk = D.getTypeObject(I);
4083
4084 // The only type information in the declarator which can come
4085 // before the declaration name is the base type of a member
4086 // pointer.
4087 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4088 continue;
4089
4090 // Rebuild the scope specifier in-place.
4091 CXXScopeSpec &SS = Chunk.Mem.Scope();
4092 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4093 return true;
4094 }
4095
4096 return false;
4097}
4098
Anders Carlsson1052fd72011-07-04 16:28:17 +00004099Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004100 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004101 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004102
4103 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004104 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004105 Dcl->setTopLevelDeclInObjCContainer();
4106
4107 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004108}
4109
Richard Smithdda56e42011-04-15 14:24:37 +00004110/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4111/// If T is the name of a class, then each of the following shall have a
4112/// name different from T:
4113/// - every static data member of class T;
4114/// - every member function of class T
4115/// - every member of class T that is itself a type;
4116/// \returns true if the declaration name violates these rules.
4117bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4118 DeclarationNameInfo NameInfo) {
4119 DeclarationName Name = NameInfo.getName();
4120
4121 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4122 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4123 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4124 return true;
4125 }
4126
4127 return false;
4128}
Douglas Gregor31feb332012-03-17 23:06:31 +00004129
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004130/// \brief Diagnose a declaration whose declarator-id has the given
4131/// nested-name-specifier.
4132///
4133/// \param SS The nested-name-specifier of the declarator-id.
4134///
4135/// \param DC The declaration context to which the nested-name-specifier
4136/// resolves.
4137///
4138/// \param Name The name of the entity being declared.
4139///
4140/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004141///
4142/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004143bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004144 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004145 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004146 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004147 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004148 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004149
4150 // If the user provided a superfluous scope specifier that refers back to the
4151 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004152 //
4153 // class X {
4154 // void X::f();
4155 // };
Richard Smitha2302242013-12-05 07:51:02 +00004156 //
4157 // Note, it was once ill-formed to give redundant qualification in all
4158 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004159 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004160 if (Cur->isRecord()) {
4161 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4162 : diag::err_member_extra_qualification)
4163 << Name << FixItHint::CreateRemoval(SS.getRange());
4164 SS.clear();
4165 } else {
4166 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4167 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004168 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004169 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004170
4171 // Check whether the qualifying scope encloses the scope of the original
4172 // declaration.
4173 if (!Cur->Encloses(DC)) {
4174 if (Cur->isRecord())
4175 Diag(Loc, diag::err_member_qualification)
4176 << Name << SS.getRange();
4177 else if (isa<TranslationUnitDecl>(DC))
4178 Diag(Loc, diag::err_invalid_declarator_global_scope)
4179 << Name << SS.getRange();
4180 else if (isa<FunctionDecl>(Cur))
4181 Diag(Loc, diag::err_invalid_declarator_in_function)
4182 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004183 else if (isa<BlockDecl>(Cur))
4184 Diag(Loc, diag::err_invalid_declarator_in_block)
4185 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004186 else
4187 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004188 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004189
Douglas Gregor31feb332012-03-17 23:06:31 +00004190 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004191 }
4192
4193 if (Cur->isRecord()) {
4194 // Cannot qualify members within a class.
4195 Diag(Loc, diag::err_member_qualification)
4196 << Name << SS.getRange();
4197 SS.clear();
4198
4199 // C++ constructors and destructors with incorrect scopes can break
4200 // our AST invariants by having the wrong underlying types. If
4201 // that's the case, then drop this declaration entirely.
4202 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4203 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4204 !Context.hasSameType(Name.getCXXNameType(),
4205 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4206 return true;
4207
4208 return false;
4209 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004210
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004211 // C++11 [dcl.meaning]p1:
4212 // [...] "The nested-name-specifier of the qualified declarator-id shall
4213 // not begin with a decltype-specifer"
4214 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4215 while (SpecLoc.getPrefix())
4216 SpecLoc = SpecLoc.getPrefix();
4217 if (dyn_cast_or_null<DecltypeType>(
4218 SpecLoc.getNestedNameSpecifier()->getAsType()))
4219 Diag(Loc, diag::err_decltype_in_declarator)
4220 << SpecLoc.getTypeLoc().getSourceRange();
4221
Douglas Gregor31feb332012-03-17 23:06:31 +00004222 return false;
4223}
4224
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004225NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4226 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004227 // TODO: consider using NameInfo for diagnostic.
4228 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4229 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004230
Chris Lattner02c04392007-07-25 00:24:17 +00004231 // All of these full declarators require an identifier. If it doesn't have
4232 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004233 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004234 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004235 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004236 diag::err_declarator_need_ident)
4237 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004238 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004239 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4240 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004241
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004242 // The scope passed in may not be a decl scope. Zip up the scope tree until
4243 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004244 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004245 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004246 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004247
John McCall99b2fe52010-04-29 23:50:39 +00004248 DeclContext *DC = CurContext;
4249 if (D.getCXXScopeSpec().isInvalid())
4250 D.setInvalidType();
4251 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004252 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4253 UPPC_DeclarationQualifier))
4254 return 0;
4255
John McCall99b2fe52010-04-29 23:50:39 +00004256 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4257 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004258 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004259 // If we could not compute the declaration context, it's because the
4260 // declaration context is dependent but does not refer to a class,
4261 // class template, or class template partial specialization. Complain
4262 // and return early, to avoid the coming semantic disaster.
4263 Diag(D.getIdentifierLoc(),
4264 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004265 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004266 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004267 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004268 }
John McCall99b2fe52010-04-29 23:50:39 +00004269 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004270
John McCall99b2fe52010-04-29 23:50:39 +00004271 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004272 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004273 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004274
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004275 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4276 Diag(D.getIdentifierLoc(),
4277 diag::err_member_def_undefined_record)
4278 << Name << DC << D.getCXXScopeSpec().getRange();
4279 D.setInvalidType();
4280 } else if (!D.getDeclSpec().isFriendSpecified()) {
4281 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4282 Name, D.getIdentifierLoc())) {
4283 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004284 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004285
4286 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004287 }
John McCall99b2fe52010-04-29 23:50:39 +00004288 }
4289
4290 // Check whether we need to rebuild the type of the given
4291 // declaration in the current instantiation.
4292 if (EnteringContext && IsDependentContext &&
4293 TemplateParamLists.size() != 0) {
4294 ContextRAII SavedContext(*this, DC);
4295 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4296 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004297 }
4298 }
Richard Smithdda56e42011-04-15 14:24:37 +00004299
4300 if (DiagnoseClassNameShadow(DC, NameInfo))
4301 // If this is a typedef, we'll end up spewing multiple diagnostics.
4302 // Just return early; it's safer.
4303 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4304 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004305
John McCall8cb7bdf2010-06-04 23:28:52 +00004306 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4307 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004308
Douglas Gregor506bd562010-12-13 22:49:22 +00004309 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4310 UPPC_DeclarationType))
4311 D.setInvalidType();
4312
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004313 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004314 ForRedeclaration);
4315
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004316 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004317 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004318 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004319 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004320
4321 // If the declaration we're planning to build will be a function
4322 // or object with linkage, then look for another declaration with
4323 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004324 //
4325 // If the declaration we're planning to build will be declared with
4326 // external linkage in the translation unit, create any builtin with
4327 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004328 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4329 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004330 else if (CurContext->isFunctionOrMethod() &&
4331 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4332 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004333 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004334 CreateBuiltins =
4335 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4336 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4337 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4338 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004339
4340 if (IsLinkageLookup)
4341 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004342
Richard Smith1c34fb72013-08-13 18:18:50 +00004343 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004344 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004345 LookupQualifiedName(Previous, DC);
4346
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004347 // C++ [dcl.meaning]p1:
4348 // When the declarator-id is qualified, the declaration shall refer to a
4349 // previously declared member of the class or namespace to which the
4350 // qualifier refers (or, in the case of a namespace, of an element of the
4351 // inline namespace set of that namespace (7.3.1)) or to a specialization
4352 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004353 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004354 // Note that we already checked the context above, and that we do not have
4355 // enough information to make sure that Previous contains the declaration
4356 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004357 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004358 // class X {
4359 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004360 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004361 // };
4362 //
Douglas Gregorad590502008-12-15 23:53:10 +00004363 // void X::f(int) { } // ill-formed
4364 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004365 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004366 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004367 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004368
4369 // C++ [dcl.meaning]p1:
4370 // [...] the member shall not merely have been introduced by a
4371 // using-declaration in the scope of the class or namespace nominated by
4372 // the nested-name-specifier of the declarator-id.
4373 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004374 }
4375
John McCall1f82f242009-11-18 22:49:29 +00004376 if (Previous.isSingleResult() &&
4377 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004378 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004379 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004380 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4381 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004382
Douglas Gregor5101c242008-12-05 18:15:24 +00004383 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004384 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004385 }
4386
Douglas Gregor83a586e2008-04-13 21:07:44 +00004387 // In C++, the previous declaration we find might be a tag type
4388 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004389 // tag type. Note that this does does not apply if we're declaring a
4390 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004391 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004392 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004393 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004394
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004395 // Check that there are no default arguments other than in the parameters
4396 // of a function declaration (C++ only).
4397 if (getLangOpts().CPlusPlus)
4398 CheckExtraCXXDefaultArguments(D);
4399
Nico Webercb4c7f42012-12-23 00:40:46 +00004400 NamedDecl *New;
4401
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004402 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004403 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004404 if (TemplateParamLists.size()) {
4405 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004406 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004407 }
Mike Stump11289f42009-09-09 15:08:12 +00004408
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004409 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004410 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004411 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004412 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004413 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004414 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004415 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4416 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004417 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004418
4419 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004420 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004421
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004422 // If this has an identifier and is not an invalid redeclaration or
4423 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004424 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004425 !(D.isRedeclaration() && New->isInvalidDecl())) {
4426 // Only make a locally-scoped extern declaration visible if it is the first
4427 // declaration of this entity. Qualified lookup for such an entity should
4428 // only find this declaration if there is no visible declaration of it.
4429 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4430 PushOnScopeChains(New, S, AddToContext);
4431 if (!AddToContext)
4432 CurContext->addHiddenDecl(New);
4433 }
Mike Stump11289f42009-09-09 15:08:12 +00004434
John McCall48871652010-08-21 09:40:31 +00004435 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004436}
4437
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004438/// Helper method to turn variable array types into constant array
4439/// types in certain situations which would otherwise be errors (for
4440/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004441static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4442 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004443 bool &SizeIsNegative,
4444 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004445 // This method tries to turn a variable array into a constant
4446 // array even when the size isn't an ICE. This is necessary
4447 // for compatibility with code that depends on gcc's buggy
4448 // constant expression folding, like struct {char x[(int)(char*)2];}
4449 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004450 Oversized = 0;
4451
4452 if (T->isDependentType())
4453 return QualType();
4454
John McCall8ccfcb52009-09-24 19:53:00 +00004455 QualifierCollector Qs;
4456 const Type *Ty = Qs.strip(T);
4457
4458 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004459 QualType Pointee = PTy->getPointeeType();
4460 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004461 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4462 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004463 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004464 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004465 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004466 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004467 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4468 QualType Inner = PTy->getInnerType();
4469 QualType FixedType =
4470 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4471 Oversized);
4472 if (FixedType.isNull()) return FixedType;
4473 FixedType = Context.getParenType(FixedType);
4474 return Qs.apply(Context, FixedType);
4475 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004476
4477 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004478 if (!VLATy)
4479 return QualType();
4480 // FIXME: We should probably handle this case
4481 if (VLATy->getElementType()->isVariablyModifiedType())
4482 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004483
Richard Smith42d3af92011-12-07 00:43:50 +00004484 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004485 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004486 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004487 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004488
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004489 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004490 if (Res.isSigned() && Res.isNegative()) {
4491 SizeIsNegative = true;
4492 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004493 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004494
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004495 // Check whether the array is too large to be addressed.
4496 unsigned ActiveSizeBits
4497 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4498 Res);
4499 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4500 Oversized = Res;
4501 return QualType();
4502 }
4503
4504 return Context.getConstantArrayType(VLATy->getElementType(),
4505 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004506}
4507
Abramo Bagnara341ab732012-11-08 14:44:42 +00004508static void
4509FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004510 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4511 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4512 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4513 DstPTL.getPointeeLoc());
4514 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004515 return;
4516 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004517 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4518 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4519 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4520 DstPTL.getInnerLoc());
4521 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4522 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004523 return;
4524 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004525 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4526 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4527 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4528 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004529 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004530 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4531 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4532 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004533}
4534
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004535/// Helper method to turn variable array types into constant array
4536/// types in certain situations which would otherwise be errors (for
4537/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004538static TypeSourceInfo*
4539TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4540 ASTContext &Context,
4541 bool &SizeIsNegative,
4542 llvm::APSInt &Oversized) {
4543 QualType FixedTy
4544 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4545 SizeIsNegative, Oversized);
4546 if (FixedTy.isNull())
4547 return 0;
4548 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4549 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4550 FixedTInfo->getTypeLoc());
4551 return FixedTInfo;
4552}
4553
Richard Smith78165b52013-01-10 23:43:47 +00004554/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004555/// that it can be found later for redeclarations. We include any extern "C"
4556/// declaration that is not visible in the translation unit here, not just
4557/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004558void
Richard Smith39b79682013-06-18 20:15:12 +00004559Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004560 if (!getLangOpts().CPlusPlus &&
4561 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4562 // Don't need to track declarations in the TU in C.
4563 return;
4564
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004565 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004566 // FIXME: There can be multiple such declarations if they are functions marked
4567 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004568 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004569}
4570
Richard Smith39b79682013-06-18 20:15:12 +00004571NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004572 if (ExternalSource) {
4573 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004574 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004575 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004576 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004577 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4578 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004579 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4580 if (Pos == LocallyScopedExternCDecls.end())
4581 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004582 }
4583 }
Richard Smith39b79682013-06-18 20:15:12 +00004584
4585 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004586 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004587}
4588
Eli Friedman574c7452009-04-07 19:37:57 +00004589/// \brief Diagnose function specifiers on a declaration of an identifier that
4590/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004591void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004592 // FIXME: We should probably indicate the identifier in question to avoid
4593 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004594 if (DS.isInlineSpecified())
4595 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004596 diag::err_inline_non_function);
4597
Richard Smithb1402ae2013-03-18 22:52:47 +00004598 if (DS.isVirtualSpecified())
4599 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004600 diag::err_virtual_non_function);
4601
Richard Smithb1402ae2013-03-18 22:52:47 +00004602 if (DS.isExplicitSpecified())
4603 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004604 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004605
Richard Smithb1402ae2013-03-18 22:52:47 +00004606 if (DS.isNoreturnSpecified())
4607 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004608 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004609}
4610
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004611NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004612Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004613 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004614 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4615 if (D.getCXXScopeSpec().isSet()) {
4616 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4617 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004618 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004619 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004620 DC = CurContext;
4621 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004622 }
4623
Richard Smithb1402ae2013-03-18 22:52:47 +00004624 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004625
Richard Smitha77a0a62011-08-15 21:04:07 +00004626 if (D.getDeclSpec().isConstexprSpecified())
4627 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4628 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004629
Douglas Gregord8f446f2010-07-13 06:37:01 +00004630 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4631 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4632 << D.getName().getSourceRange();
4633 return 0;
4634 }
4635
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004636 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004637 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004638
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004639 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004640 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004641
Richard Smith3f1b5d02011-05-05 21:57:07 +00004642 CheckTypedefForVariablyModifiedType(S, NewTD);
4643
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004644 bool Redeclaration = D.isRedeclaration();
4645 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4646 D.setRedeclaration(Redeclaration);
4647 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004648}
4649
Richard Smith3f1b5d02011-05-05 21:57:07 +00004650void
4651Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004652 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4653 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004654 // Note that variably modified types must be fixed before merging the decl so
4655 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004656 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4657 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004658 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004659 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004660
Chris Lattner9fecd742009-04-19 05:21:20 +00004661 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004662 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004663 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004664 TypeSourceInfo *FixedTInfo =
4665 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4666 SizeIsNegative,
4667 Oversized);
4668 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004669 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004670 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004671 } else {
4672 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004673 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004674 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004675 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004676 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004677 Diag(NewTD->getLocation(), diag::err_array_too_large)
4678 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004679 else
Richard Smithdda56e42011-04-15 14:24:37 +00004680 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004681 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004682 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004683 }
4684 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004685}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004686
Richard Smith3f1b5d02011-05-05 21:57:07 +00004687
4688/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4689/// declares a typedef-name, either using the 'typedef' type specifier or via
4690/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4691NamedDecl*
4692Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4693 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004694 // Merge the decl with the existing one if appropriate. If the decl is
4695 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004696 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4697 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004698 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004699 if (!Previous.empty()) {
4700 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004701 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004702 }
4703
Douglas Gregor27821ce2009-07-07 16:35:42 +00004704 // If this is the C FILE type, notify the AST context.
4705 if (IdentifierInfo *II = NewTD->getIdentifier())
4706 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004707 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004708 if (II->isStr("FILE"))
4709 Context.setFILEDecl(NewTD);
4710 else if (II->isStr("jmp_buf"))
4711 Context.setjmp_bufDecl(NewTD);
4712 else if (II->isStr("sigjmp_buf"))
4713 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004714 else if (II->isStr("ucontext_t"))
4715 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004716 }
4717
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004718 return NewTD;
4719}
4720
Douglas Gregor5d68a202009-02-24 19:23:27 +00004721/// \brief Determines whether the given declaration is an out-of-scope
4722/// previous declaration.
4723///
4724/// This routine should be invoked when name lookup has found a
4725/// previous declaration (PrevDecl) that is not in the scope where a
4726/// new declaration by the same name is being introduced. If the new
4727/// declaration occurs in a local scope, previous declarations with
4728/// linkage may still be considered previous declarations (C99
4729/// 6.2.2p4-5, C++ [basic.link]p6).
4730///
4731/// \param PrevDecl the previous declaration found by name
4732/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004733///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004734/// \param DC the context in which the new declaration is being
4735/// declared.
4736///
4737/// \returns true if PrevDecl is an out-of-scope previous declaration
4738/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004739static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004740isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4741 ASTContext &Context) {
4742 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004743 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004744
Douglas Gregoreddf4332009-02-24 20:03:32 +00004745 if (!PrevDecl->hasLinkage())
4746 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004747
David Blaikiebbafb8a2012-03-11 07:00:24 +00004748 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004749 // C++ [basic.link]p6:
4750 // If there is a visible declaration of an entity with linkage
4751 // having the same name and type, ignoring entities declared
4752 // outside the innermost enclosing namespace scope, the block
4753 // scope declaration declares that same entity and receives the
4754 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004755 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004756 if (!OuterContext->isFunctionOrMethod())
4757 // This rule only applies to block-scope declarations.
4758 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004759
4760 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4761 if (PrevOuterContext->isRecord())
4762 // We found a member function: ignore it.
4763 return false;
4764
4765 // Find the innermost enclosing namespace for the new and
4766 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004767 OuterContext = OuterContext->getEnclosingNamespaceContext();
4768 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004769
Douglas Gregorfcee9462010-08-27 22:55:10 +00004770 // The previous declaration is in a different namespace, so it
4771 // isn't the same function.
4772 if (!OuterContext->Equals(PrevOuterContext))
4773 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004774 }
4775
Douglas Gregor5d68a202009-02-24 19:23:27 +00004776 return true;
4777}
4778
John McCall3e11ebe2010-03-15 10:12:16 +00004779static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4780 CXXScopeSpec &SS = D.getCXXScopeSpec();
4781 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004782 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004783}
4784
John McCall31168b02011-06-15 23:02:42 +00004785bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4786 QualType type = decl->getType();
4787 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4788 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4789 // Various kinds of declaration aren't allowed to be __autoreleasing.
4790 unsigned kind = -1U;
4791 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4792 if (var->hasAttr<BlocksAttr>())
4793 kind = 0; // __block
4794 else if (!var->hasLocalStorage())
4795 kind = 1; // global
4796 } else if (isa<ObjCIvarDecl>(decl)) {
4797 kind = 3; // ivar
4798 } else if (isa<FieldDecl>(decl)) {
4799 kind = 2; // field
4800 }
4801
4802 if (kind != -1U) {
4803 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4804 << kind;
4805 }
4806 } else if (lifetime == Qualifiers::OCL_None) {
4807 // Try to infer lifetime.
4808 if (!type->isObjCLifetimeType())
4809 return false;
4810
4811 lifetime = type->getObjCARCImplicitLifetime();
4812 type = Context.getLifetimeQualifiedType(type, lifetime);
4813 decl->setType(type);
4814 }
4815
4816 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4817 // Thread-local variables cannot have lifetime.
4818 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004819 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004820 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004821 << var->getType();
4822 return true;
4823 }
4824 }
4825
4826 return false;
4827}
4828
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004829static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00004830 // Ensure that an auto decl is deduced otherwise the checks below might cache
4831 // the wrong linkage.
4832 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4833
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004834 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004835 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004836 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004837 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4838 ND.dropAttr<WeakAttr>();
4839 }
4840 }
4841 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004842 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004843 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4844 ND.dropAttr<WeakRefAttr>();
4845 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004846 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004847
4848 // 'selectany' only applies to externally visible varable declarations.
4849 // It does not apply to functions.
4850 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4851 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4852 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4853 ND.dropAttr<SelectAnyAttr>();
4854 }
4855 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004856}
4857
John McCallc87d9722013-04-02 02:48:58 +00004858/// Given that we are within the definition of the given function,
4859/// will that definition behave like C99's 'inline', where the
4860/// definition is discarded except for optimization purposes?
4861static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4862 // Try to avoid calling GetGVALinkageForFunction.
4863
4864 // All cases of this require the 'inline' keyword.
4865 if (!FD->isInlined()) return false;
4866
4867 // This is only possible in C++ with the gnu_inline attribute.
4868 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4869 return false;
4870
4871 // Okay, go ahead and call the relatively-more-expensive function.
4872
4873#ifndef NDEBUG
4874 // AST quite reasonably asserts that it's working on a function
4875 // definition. We don't really have a way to tell it that we're
4876 // currently defining the function, so just lie to it in +Asserts
4877 // builds. This is an awful hack.
4878 FD->setLazyBody(1);
4879#endif
4880
4881 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4882
4883#ifndef NDEBUG
4884 FD->setLazyBody(0);
4885#endif
4886
4887 return isC99Inline;
4888}
4889
Richard Smithac974a32013-06-30 09:48:50 +00004890/// Determine whether a variable is extern "C" prior to attaching
4891/// an initializer. We can't just call isExternC() here, because that
4892/// will also compute and cache whether the declaration is externally
4893/// visible, which might change when we attach the initializer.
4894///
4895/// This can only be used if the declaration is known to not be a
4896/// redeclaration of an internal linkage declaration.
4897///
4898/// For instance:
4899///
4900/// auto x = []{};
4901///
4902/// Attaching the initializer here makes this declaration not externally
4903/// visible, because its type has internal linkage.
4904///
4905/// FIXME: This is a hack.
4906template<typename T>
4907static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4908 if (S.getLangOpts().CPlusPlus) {
4909 // In C++, the overloadable attribute negates the effects of extern "C".
4910 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4911 return false;
4912 }
4913 return D->isExternC();
4914}
4915
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004916static bool shouldConsiderLinkage(const VarDecl *VD) {
4917 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4918 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004919 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004920 if (DC->isFileContext())
4921 return true;
4922 if (DC->isRecord())
4923 return false;
4924 llvm_unreachable("Unexpected context");
4925}
4926
4927static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4928 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4929 if (DC->isFileContext() || DC->isFunctionOrMethod())
4930 return true;
4931 if (DC->isRecord())
4932 return false;
4933 llvm_unreachable("Unexpected context");
4934}
4935
Richard Smith541b38b2013-09-20 01:15:31 +00004936/// Adjust the \c DeclContext for a function or variable that might be a
4937/// function-local external declaration.
4938bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4939 if (!DC->isFunctionOrMethod())
4940 return false;
4941
4942 // If this is a local extern function or variable declared within a function
4943 // template, don't add it into the enclosing namespace scope until it is
4944 // instantiated; it might have a dependent type right now.
4945 if (DC->isDependentContext())
4946 return true;
4947
4948 // C++11 [basic.link]p7:
4949 // When a block scope declaration of an entity with linkage is not found to
4950 // refer to some other declaration, then that entity is a member of the
4951 // innermost enclosing namespace.
4952 //
4953 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4954 // semantically-enclosing namespace, not a lexically-enclosing one.
4955 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4956 DC = DC->getParent();
4957 return true;
4958}
4959
Larisse Voufo39a1e502013-08-06 01:03:05 +00004960NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00004961Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004962 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004963 MultiTemplateParamsArg TemplateParamLists,
4964 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004965 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004966 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004967
Douglas Gregorc4df4072010-04-19 22:54:31 +00004968 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00004969 VarDecl::StorageClass SC =
4970 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00004971
Richard Smith541b38b2013-09-20 01:15:31 +00004972 DeclContext *OriginalDC = DC;
4973 bool IsLocalExternDecl = SC == SC_Extern &&
4974 adjustContextForLocalExternDecl(DC);
4975
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00004976 if (getLangOpts().OpenCL) {
4977 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
4978 QualType NR = R;
4979 while (NR->isPointerType()) {
4980 if (NR->isFunctionPointerType()) {
4981 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
4982 D.setInvalidType();
4983 break;
4984 }
4985 NR = NR->getPointeeType();
4986 }
4987
4988 if (!getOpenCLOptions().cl_khr_fp16) {
4989 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4990 // half array type (unless the cl_khr_fp16 extension is enabled).
4991 if (Context.getBaseElementType(R)->isHalfType()) {
4992 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4993 D.setInvalidType();
4994 }
Joey Goulydd7f4562013-01-23 11:56:20 +00004995 }
4996 }
4997
Douglas Gregorc4df4072010-04-19 22:54:31 +00004998 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004999 // mutable can only appear on non-static class members, so it's always
5000 // an error here
5001 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005002 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005003 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005004 }
John McCallc87d9722013-04-02 02:48:58 +00005005
Richard Smithf2c9afc2013-06-17 01:34:01 +00005006 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5007 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5008 D.getDeclSpec().getStorageClassSpecLoc())) {
5009 // In C++11, the 'register' storage class specifier is deprecated.
5010 // Suppress the warning in system macros, it's used in macros in some
5011 // popular C system headers, such as in glibc's htonl() macro.
5012 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5013 diag::warn_deprecated_register)
5014 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5015 }
5016
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005017 IdentifierInfo *II = Name.getAsIdentifierInfo();
5018 if (!II) {
5019 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00005020 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005021 return 0;
5022 }
5023
Richard Smithb1402ae2013-03-18 22:52:47 +00005024 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00005025
Douglas Gregor212cab32009-03-11 20:22:50 +00005026 if (!DC->isRecord() && S->getFnParent() == 0) {
5027 // C99 6.9p2: The storage-class specifiers auto and register shall not
5028 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00005029 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005030 // If this is a register variable with an asm label specified, then this
5031 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00005032 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005033 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5034 else
5035 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005036 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005037 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005038 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005039
David Blaikiebbafb8a2012-03-11 07:00:24 +00005040 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005041 // Set up the special work-group-local storage class for variables in the
5042 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005043 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005044 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005045 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005046
Guy Benyei61054192013-02-07 10:55:47 +00005047 // OpenCL v1.2 s6.9.b p4:
5048 // The sampler type cannot be used with the __local and __global address
5049 // space qualifiers.
5050 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5051 R.getAddressSpace() == LangAS::opencl_global)) {
5052 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5053 }
5054
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005055 // OpenCL 1.2 spec, p6.9 r:
5056 // The event type cannot be used to declare a program scope variable.
5057 // The event type cannot be used with the __local, __constant and __global
5058 // address space qualifiers.
5059 if (R->isEventT()) {
5060 if (S->getParent() == 0) {
5061 Diag(D.getLocStart(), diag::err_event_t_global_var);
5062 D.setInvalidType();
5063 }
5064
5065 if (R.getAddressSpace()) {
5066 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5067 D.setInvalidType();
5068 }
5069 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005070 }
5071
Larisse Voufo39a1e502013-08-06 01:03:05 +00005072 bool IsExplicitSpecialization = false;
5073 bool IsVariableTemplateSpecialization = false;
5074 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005075 bool IsVariableTemplate = false;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005076 VarDecl *NewVD = 0;
5077 VarTemplateDecl *NewTemplate = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00005078 TemplateParameterList *TemplateParams = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005079 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005080 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005081 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005082 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005083
5084 if (D.isInvalidType())
5085 NewVD->setInvalidDecl();
5086 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005087 bool Invalid = false;
5088
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005089 if (DC->isRecord() && !CurContext->isRecord()) {
5090 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005091 switch (SC) {
5092 case SC_None:
5093 break;
5094 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005095 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5096 diag::err_static_out_of_line)
5097 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005098 break;
5099 case SC_Auto:
5100 case SC_Register:
5101 case SC_Extern:
5102 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5103 // to names of variables declared in a block or to function parameters.
5104 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5105 // of class members
5106
5107 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5108 diag::err_storage_class_for_static_member)
5109 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5110 break;
5111 case SC_PrivateExtern:
5112 llvm_unreachable("C storage class in c++!");
5113 case SC_OpenCLWorkGroupLocal:
5114 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005115 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005116 }
5117
Richard Smith42973752012-02-16 20:41:22 +00005118 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005119 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5120 if (RD->isLocalClass())
5121 Diag(D.getIdentifierLoc(),
5122 diag::err_static_data_member_not_allowed_in_local_class)
5123 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005124
Richard Smith42973752012-02-16 20:41:22 +00005125 // C++98 [class.union]p1: If a union contains a static data member,
5126 // the program is ill-formed. C++11 drops this restriction.
5127 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005128 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005129 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005130 ? diag::warn_cxx98_compat_static_data_member_in_union
5131 : diag::ext_static_data_member_in_union) << Name;
5132 // We conservatively disallow static data members in anonymous structs.
5133 else if (!RD->getDeclName())
5134 Diag(D.getIdentifierLoc(),
5135 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005136 << Name << RD->isUnion();
5137 }
5138 }
5139
5140 // Match up the template parameter lists with the scope specifier, then
5141 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005142 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5143 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5144 D.getCXXScopeSpec(), TemplateParamLists,
5145 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005146
Richard Smithbeef3452014-01-16 23:39:20 +00005147 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
5148 !TemplateParams) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005149 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5150
5151 // We have encountered something that the user meant to be a
5152 // specialization (because it has explicitly-specified template
5153 // arguments) but that was not introduced with a "template<>" (or had
5154 // too few of them).
5155 // FIXME: Differentiate between attempts for explicit instantiations
5156 // (starting with "template") and the rest.
5157 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5158 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5159 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5160 "template<> ");
Richard Smith72db5632014-01-25 21:32:06 +00005161 IsExplicitSpecialization = true;
Richard Smithbeef3452014-01-16 23:39:20 +00005162 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(),
5163 SourceLocation(), 0, 0,
5164 SourceLocation());
5165 }
5166
5167 if (TemplateParams) {
5168 if (!TemplateParams->size() &&
5169 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5170 // There is an extraneous 'template<>' for this variable. Complain
5171 // about it, but allow the declaration of the variable.
5172 Diag(TemplateParams->getTemplateLoc(),
5173 diag::err_template_variable_noparams)
5174 << II
5175 << SourceRange(TemplateParams->getTemplateLoc(),
5176 TemplateParams->getRAngleLoc());
5177 TemplateParams = 0;
5178 } else {
5179 // Only C++1y supports variable templates (N3651).
5180 Diag(D.getIdentifierLoc(),
5181 getLangOpts().CPlusPlus1y
5182 ? diag::warn_cxx11_compat_variable_template
5183 : diag::ext_variable_template);
5184
5185 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5186 // This is an explicit specialization or a partial specialization.
5187 // FIXME: Check that we can declare a specialization here.
5188 IsVariableTemplateSpecialization = true;
5189 IsPartialSpecialization = TemplateParams->size() > 0;
5190 } else { // if (TemplateParams->size() > 0)
5191 // This is a template declaration.
5192 IsVariableTemplate = true;
5193
5194 // Check that we can declare a template here.
5195 if (CheckTemplateDeclScope(S, TemplateParams))
5196 return 0;
5197 }
5198 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005199 }
Mike Stump11289f42009-09-09 15:08:12 +00005200
Larisse Voufo39a1e502013-08-06 01:03:05 +00005201 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005202 SourceLocation TemplateKWLoc =
5203 TemplateParamLists.size() > 0
5204 ? TemplateParamLists[0]->getTemplateLoc()
5205 : SourceLocation();
5206 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005207 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005208 IsPartialSpecialization);
5209 if (Res.isInvalid())
5210 return 0;
5211 NewVD = cast<VarDecl>(Res.get());
5212 AddToScope = false;
5213 } else
5214 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5215 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005216
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005217 // If this is supposed to be a variable template, create it as such.
5218 if (IsVariableTemplate) {
5219 NewTemplate =
5220 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005221 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005222 NewVD->setDescribedVarTemplate(NewTemplate);
5223 }
5224
Richard Smithb2bc2e62011-02-21 20:05:19 +00005225 // If this decl has an auto type in need of deduction, make a note of the
5226 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005227 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005228 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005229
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005230 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005231 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005232 if (NewTemplate)
5233 NewTemplate->setInvalidDecl();
5234 }
Mike Stump11289f42009-09-09 15:08:12 +00005235
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005236 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005237
Richard Smith72db5632014-01-25 21:32:06 +00005238 // If we have any template parameter lists that don't directly belong to
5239 // the variable (matching the scope specifier), store them.
5240 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5241 if (TemplateParamLists.size() > VDTemplateParamLists)
Larisse Voufo39a1e502013-08-06 01:03:05 +00005242 NewVD->setTemplateParameterListsInfo(
Richard Smith72db5632014-01-25 21:32:06 +00005243 Context, TemplateParamLists.size() - VDTemplateParamLists,
5244 TemplateParamLists.data());
Richard Smitha77a0a62011-08-15 21:04:07 +00005245
Richard Smith6331c402012-02-13 22:16:19 +00005246 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005247 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005248 }
5249
Douglas Gregor41866812011-09-12 18:37:38 +00005250 // Set the lexical context. If the declarator has a C++ scope specifier, the
5251 // lexical context will be different from the semantic context.
5252 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005253 if (NewTemplate)
5254 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005255
Richard Smith541b38b2013-09-20 01:15:31 +00005256 if (IsLocalExternDecl)
5257 NewVD->setLocalExternDecl();
5258
Richard Smithb4a9e862013-04-12 22:46:28 +00005259 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005260 if (NewVD->hasLocalStorage()) {
5261 // C++11 [dcl.stc]p4:
5262 // When thread_local is applied to a variable of block scope the
5263 // storage-class-specifier static is implied if it does not appear
5264 // explicitly.
5265 // Core issue: 'static' is not implied if the variable is declared
5266 // 'extern'.
5267 if (SCSpec == DeclSpec::SCS_unspecified &&
5268 TSCS == DeclSpec::TSCS_thread_local &&
5269 DC->isFunctionOrMethod())
5270 NewVD->setTSCSpec(TSCS);
5271 else
5272 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5273 diag::err_thread_non_global)
5274 << DeclSpec::getSpecifierName(TSCS);
5275 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005276 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5277 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005278 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005279 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005280 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005281
John McCallc87d9722013-04-02 02:48:58 +00005282 // C99 6.7.4p3
5283 // An inline definition of a function with external linkage shall
5284 // not contain a definition of a modifiable object with static or
5285 // thread storage duration...
5286 // We only apply this when the function is required to be defined
5287 // elsewhere, i.e. when the function is not 'extern inline'. Note
5288 // that a local variable with thread storage duration still has to
5289 // be marked 'static'. Also note that it's possible to get these
5290 // semantics in C++ using __attribute__((gnu_inline)).
5291 if (SC == SC_Static && S->getFnParent() != 0 &&
5292 !NewVD->getType().isConstQualified()) {
5293 FunctionDecl *CurFD = getCurFunctionDecl();
5294 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5295 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5296 diag::warn_static_local_in_extern_inline);
5297 MaybeSuggestAddingStaticToDecl(CurFD);
5298 }
5299 }
5300
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005301 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005302 if (IsVariableTemplateSpecialization)
5303 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5304 << (IsPartialSpecialization ? 1 : 0)
5305 << FixItHint::CreateRemoval(
5306 D.getDeclSpec().getModulePrivateSpecLoc());
5307 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005308 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5309 << 2
5310 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005311 else if (NewVD->hasLocalStorage())
5312 Diag(NewVD->getLocation(), diag::err_module_private_local)
5313 << 0 << NewVD->getDeclName()
5314 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5315 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005316 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005317 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005318 if (NewTemplate)
5319 NewTemplate->setModulePrivate();
5320 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005321 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005322
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005323 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005324 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005325
Richard Smith848e1f12013-02-01 08:12:08 +00005326 if (NewVD->hasAttrs())
5327 CheckAlignasUnderalignment(NewVD);
5328
Peter Collingbournec6b08572012-08-28 20:37:50 +00005329 if (getLangOpts().CUDA) {
5330 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5331 // storage [duration]."
5332 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005333 (NewVD->hasAttr<CUDASharedAttr>() ||
5334 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005335 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005336 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005337 }
5338
John McCall31168b02011-06-15 23:02:42 +00005339 // In auto-retain/release, infer strong retension for variables of
5340 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005341 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005342 NewVD->setInvalidDecl();
5343
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005344 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005345 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005346 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005347 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005348 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005349 if (S->getFnParent() != 0) {
5350 switch (SC) {
5351 case SC_None:
5352 case SC_Auto:
5353 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5354 break;
5355 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005356 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005357 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5358 break;
5359 case SC_Static:
5360 case SC_Extern:
5361 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005362 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005363 break;
5364 }
5365 }
5366
5367 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005368 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005369 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5370 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5371 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5372 if (I != ExtnameUndeclaredIdentifiers.end()) {
5373 NewVD->addAttr(I->second);
5374 ExtnameUndeclaredIdentifiers.erase(I);
5375 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005376 }
5377
John McCalla2a3f7d2010-03-16 21:48:18 +00005378 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005379 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005380 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005381
John McCall1f82f242009-11-18 22:49:29 +00005382 // Don't consider existing declarations that are in a different
5383 // scope and are out-of-semantic-context declarations (if the new
5384 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005385 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5386 D.getCXXScopeSpec().isNotEmpty() ||
5387 IsExplicitSpecialization ||
5388 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005389
Richard Smith1c34fb72013-08-13 18:18:50 +00005390 // Check whether the previous declaration is in the same block scope. This
5391 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5392 if (getLangOpts().CPlusPlus &&
5393 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5394 NewVD->setPreviousDeclInSameBlockScope(
5395 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005396 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005397
David Blaikiebbafb8a2012-03-11 07:00:24 +00005398 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005399 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5400 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005401 // If this is an explicit specialization of a static data member, check it.
5402 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5403 CheckMemberSpecialization(NewVD, Previous))
5404 NewVD->setInvalidDecl();
5405
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005406 // Merge the decl with the existing one if appropriate.
5407 if (!Previous.empty()) {
5408 if (Previous.isSingleResult() &&
5409 isa<FieldDecl>(Previous.getFoundDecl()) &&
5410 D.getCXXScopeSpec().isSet()) {
5411 // The user tried to define a non-static data member
5412 // out-of-line (C++ [dcl.meaning]p1).
5413 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5414 << D.getCXXScopeSpec().getRange();
5415 Previous.clear();
5416 NewVD->setInvalidDecl();
5417 }
5418 } else if (D.getCXXScopeSpec().isSet()) {
5419 // No previous declaration in the qualifying scope.
5420 Diag(D.getIdentifierLoc(), diag::err_no_member)
5421 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005422 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005423 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005424 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005425
Richard Smithbeef3452014-01-16 23:39:20 +00005426 if (!IsVariableTemplateSpecialization)
5427 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005428
Richard Smithbeef3452014-01-16 23:39:20 +00005429 if (NewTemplate) {
5430 VarTemplateDecl *PrevVarTemplate =
5431 NewVD->getPreviousDecl()
5432 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5433 : 0;
5434
5435 // Check the template parameter list of this declaration, possibly
5436 // merging in the template parameter list from the previous variable
5437 // template declaration.
5438 if (CheckTemplateParameterList(
5439 TemplateParams,
5440 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5441 : 0,
5442 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5443 DC->isDependentContext())
5444 ? TPC_ClassTemplateMember
5445 : TPC_VarTemplate))
5446 NewVD->setInvalidDecl();
5447
5448 // If we are providing an explicit specialization of a static variable
5449 // template, make a note of that.
5450 if (PrevVarTemplate &&
5451 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5452 PrevVarTemplate->setMemberSpecialization();
5453 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005454 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005455
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005456 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005457
Richard Smithac974a32013-06-30 09:48:50 +00005458 // If this is the first declaration of an extern C variable, update
5459 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005460 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005461 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005462 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005463
Reid Klecknerd8110b62013-09-10 20:14:30 +00005464 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005465 Decl *ManglingContextDecl;
5466 if (MangleNumberingContext *MCtx =
5467 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5468 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00005469 Context.setManglingNumber(
5470 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00005471 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005472 }
5473 }
5474
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005475 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005476 if (NewVD->isInvalidDecl())
5477 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005478 ActOnDocumentableDecl(NewTemplate);
5479 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005480 }
5481
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005482 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005483}
5484
John McCalldf8b37c2010-03-22 09:20:08 +00005485/// \brief Diagnose variable or built-in function shadowing. Implements
5486/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005487///
John McCalldf8b37c2010-03-22 09:20:08 +00005488/// This method is called whenever a VarDecl is added to a "useful"
5489/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005490///
John McCall2d8c7602010-03-20 04:12:52 +00005491/// \param S the scope in which the shadowing name is being declared
5492/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005493///
John McCalldf8b37c2010-03-22 09:20:08 +00005494void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005495 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005496 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005497 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005498 return;
5499
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005500 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005501 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005502 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005503
5504 DeclContext *NewDC = D->getDeclContext();
5505
John McCall2d8c7602010-03-20 04:12:52 +00005506 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005507 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005508 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005509
John McCalla2a3f7d2010-03-16 21:48:18 +00005510 NamedDecl* ShadowedDecl = R.getFoundDecl();
5511 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5512 return;
5513
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005514 // Fields are not shadowed by variables in C++ static methods.
5515 if (isa<FieldDecl>(ShadowedDecl))
5516 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5517 if (MD->isStatic())
5518 return;
5519
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005520 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5521 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005522 // For shadowing external vars, make sure that we point to the global
5523 // declaration, not a locally scoped extern declaration.
Aaron Ballman86c93902014-03-06 23:45:36 +00005524 for (auto I : shadowedVar->redecls())
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005525 if (I->isFileVarDecl()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00005526 ShadowedDecl = I;
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005527 break;
5528 }
5529 }
5530
5531 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5532
John McCall2d8c7602010-03-20 04:12:52 +00005533 // Only warn about certain kinds of shadowing for class members.
5534 if (NewDC && NewDC->isRecord()) {
5535 // In particular, don't warn about shadowing non-class members.
5536 if (!OldDC->isRecord())
5537 return;
5538
5539 // TODO: should we warn about static data members shadowing
5540 // static data members from base classes?
5541
5542 // TODO: don't diagnose for inaccessible shadowed members.
5543 // This is hard to do perfectly because we might friend the
5544 // shadowing context, but that's just a false negative.
5545 }
5546
5547 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005548 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005549 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005550 if (isa<FieldDecl>(ShadowedDecl))
5551 Kind = 3; // field
5552 else
5553 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005554 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005555 Kind = 1; // global
5556 else
5557 Kind = 0; // local
5558
John McCall2d8c7602010-03-20 04:12:52 +00005559 DeclarationName Name = R.getLookupName();
5560
John McCalla2a3f7d2010-03-16 21:48:18 +00005561 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005562 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5563 return;
John McCall2d8c7602010-03-20 04:12:52 +00005564 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005565 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5566}
5567
John McCalldf8b37c2010-03-22 09:20:08 +00005568/// \brief Check -Wshadow without the advantage of a previous lookup.
5569void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005570 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005571 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005572 return;
5573
John McCalldf8b37c2010-03-22 09:20:08 +00005574 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5575 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5576 LookupName(R, S);
5577 CheckShadow(S, D, R);
5578}
5579
Richard Smithac974a32013-06-30 09:48:50 +00005580/// Check for conflict between this global or extern "C" declaration and
5581/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005582template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005583static bool checkGlobalOrExternCConflict(
5584 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5585 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5586 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005587
Richard Smithac974a32013-06-30 09:48:50 +00005588 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5589 // The common case: this global doesn't conflict with any extern "C"
5590 // declaration.
5591 return false;
5592 }
5593
5594 if (Prev) {
5595 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5596 // Both the old and new declarations have C language linkage. This is a
5597 // redeclaration.
5598 Previous.clear();
5599 Previous.addDecl(Prev);
5600 return true;
5601 }
5602
5603 // This is a global, non-extern "C" declaration, and there is a previous
5604 // non-global extern "C" declaration. Diagnose if this is a variable
5605 // declaration.
5606 if (!isa<VarDecl>(ND))
5607 return false;
5608 } else {
5609 // The declaration is extern "C". Check for any declaration in the
5610 // translation unit which might conflict.
5611 if (IsGlobal) {
5612 // We have already performed the lookup into the translation unit.
5613 IsGlobal = false;
5614 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5615 I != E; ++I) {
5616 if (isa<VarDecl>(*I)) {
5617 Prev = *I;
5618 break;
5619 }
5620 }
5621 } else {
5622 DeclContext::lookup_result R =
5623 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5624 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5625 I != E; ++I) {
5626 if (isa<VarDecl>(*I)) {
5627 Prev = *I;
5628 break;
5629 }
5630 // FIXME: If we have any other entity with this name in global scope,
5631 // the declaration is ill-formed, but that is a defect: it breaks the
5632 // 'stat' hack, for instance. Only variables can have mangled name
5633 // clashes with extern "C" declarations, so only they deserve a
5634 // diagnostic.
5635 }
5636 }
5637
5638 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005639 return false;
5640 }
5641
Richard Smithac974a32013-06-30 09:48:50 +00005642 // Use the first declaration's location to ensure we point at something which
5643 // is lexically inside an extern "C" linkage-spec.
5644 assert(Prev && "should have found a previous declaration to diagnose");
5645 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005646 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005647 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005648 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005649
5650 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5651 << IsGlobal << ND;
5652 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5653 << IsGlobal;
5654 return false;
5655}
5656
5657/// Apply special rules for handling extern "C" declarations. Returns \c true
5658/// if we have found that this is a redeclaration of some prior entity.
5659///
5660/// Per C++ [dcl.link]p6:
5661/// Two declarations [for a function or variable] with C language linkage
5662/// with the same name that appear in different scopes refer to the same
5663/// [entity]. An entity with C language linkage shall not be declared with
5664/// the same name as an entity in global scope.
5665template<typename T>
5666static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5667 LookupResult &Previous) {
5668 if (!S.getLangOpts().CPlusPlus) {
5669 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005670 // variable declared in function scope. We don't need this in C++, because
5671 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005672 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5673 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5674 Previous.clear();
5675 Previous.addDecl(Prev);
5676 return true;
5677 }
5678 }
5679 return false;
5680 }
5681
5682 // A declaration in the translation unit can conflict with an extern "C"
5683 // declaration.
5684 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5685 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5686
5687 // An extern "C" declaration can conflict with a declaration in the
5688 // translation unit or can be a redeclaration of an extern "C" declaration
5689 // in another scope.
5690 if (isIncompleteDeclExternC(S,ND))
5691 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5692
5693 // Neither global nor extern "C": nothing to do.
5694 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005695}
5696
Richard Smith27d807c2013-04-30 13:56:41 +00005697void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005698 // If the decl is already known invalid, don't check it.
5699 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005700 return;
Mike Stump11289f42009-09-09 15:08:12 +00005701
Abramo Bagnara341ab732012-11-08 14:44:42 +00005702 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5703 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005704
Richard Smith27d807c2013-04-30 13:56:41 +00005705 // Defer checking an 'auto' type until its initializer is attached.
5706 if (T->isUndeducedType())
5707 return;
5708
John McCall8b07ec22010-05-15 11:32:37 +00005709 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005710 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5711 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005712 T = Context.getObjCObjectPointerType(T);
5713 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005714 }
Mike Stump11289f42009-09-09 15:08:12 +00005715
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005716 // Emit an error if an address space was applied to decl with local storage.
5717 // This includes arrays of objects with address space qualifiers, but not
5718 // automatic variables that point to other address spaces.
5719 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005720 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005721 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005722 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005723 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005724 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005725
Tanya Lattner713eef42013-04-05 20:14:50 +00005726 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5727 // __constant address space.
5728 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5729 && T.getAddressSpace() != LangAS::opencl_constant
5730 && !T->isSamplerT()){
5731 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5732 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005733 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005734 }
5735
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005736 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5737 // scope.
5738 if ((getLangOpts().OpenCLVersion >= 120)
5739 && NewVD->isStaticLocal()) {
5740 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5741 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005742 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005743 }
5744
Mike Stumpca5ae662009-04-14 00:57:29 +00005745 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005746 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005747 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005748 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005749 else {
5750 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005751 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005752 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005753 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005754
Chris Lattner9fecd742009-04-19 05:21:20 +00005755 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005756 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005757 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005758 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005759
Chris Lattner9fecd742009-04-19 05:21:20 +00005760 if ((isVM && NewVD->hasLinkage()) ||
5761 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005762 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005763 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005764 TypeSourceInfo *FixedTInfo =
5765 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5766 SizeIsNegative, Oversized);
5767 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005768 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005769 // FIXME: This won't give the correct result for
5770 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005771 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005772
Anders Carlsson6c885802009-02-28 21:56:50 +00005773 if (NewVD->isFileVarDecl())
5774 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005775 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005776 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005777 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005778 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005779 else
5780 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005781 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005782 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005783 return;
Mike Stump11289f42009-09-09 15:08:12 +00005784 }
5785
Abramo Bagnara341ab732012-11-08 14:44:42 +00005786 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005787 if (NewVD->isFileVarDecl())
5788 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5789 else
5790 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005791 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005792 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005793 }
Mike Stump11289f42009-09-09 15:08:12 +00005794
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005795 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005796 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005797 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005798 }
5799
David Majnemer0ffa3312013-05-29 00:56:45 +00005800 if (T->isVoidType()) {
5801 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5802 // of objects and functions.
5803 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5804 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5805 << T;
5806 NewVD->setInvalidDecl();
5807 return;
5808 }
Richard Smith27d807c2013-04-30 13:56:41 +00005809 }
5810
5811 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5812 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5813 NewVD->setInvalidDecl();
5814 return;
5815 }
5816
5817 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5818 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5819 NewVD->setInvalidDecl();
5820 return;
5821 }
5822
5823 if (NewVD->isConstexpr() && !T->isDependentType() &&
5824 RequireLiteralType(NewVD->getLocation(), T,
5825 diag::err_constexpr_var_non_literal)) {
5826 // Can't perform this check until the type is deduced.
5827 NewVD->setInvalidDecl();
5828 return;
5829 }
5830}
5831
5832/// \brief Perform semantic checking on a newly-created variable
5833/// declaration.
5834///
5835/// This routine performs all of the type-checking required for a
5836/// variable declaration once it has been built. It is used both to
5837/// check variables after they have been parsed and their declarators
5838/// have been translated into a declaration, and to check variables
5839/// that have been instantiated from a template.
5840///
5841/// Sets NewVD->isInvalidDecl() if an error was encountered.
5842///
5843/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005844bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005845 CheckVariableDeclarationType(NewVD);
5846
5847 // If the decl is already known invalid, don't check it.
5848 if (NewVD->isInvalidDecl())
5849 return false;
5850
John McCallb65e8fe2013-04-01 18:34:28 +00005851 // If we did not find anything by this name, look for a non-visible
5852 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005853 if (Previous.empty() &&
5854 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005855 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005856
Douglas Gregor3552dab2013-01-09 00:47:56 +00005857 // Filter out any non-conflicting previous declarations.
5858 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5859
John McCall1f82f242009-11-18 22:49:29 +00005860 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005861 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005862 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005863 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005864 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005865}
5866
Douglas Gregor36d1b142009-10-06 17:59:45 +00005867/// \brief Data used with FindOverriddenMethod
5868struct FindOverriddenMethodData {
5869 Sema *S;
5870 CXXMethodDecl *Method;
5871};
5872
5873/// \brief Member lookup function that determines whether a given C++
5874/// method overrides a method in a base class, to be used with
5875/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005876static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005877 CXXBasePath &Path,
5878 void *UserData) {
5879 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005880
Douglas Gregor36d1b142009-10-06 17:59:45 +00005881 FindOverriddenMethodData *Data
5882 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005883
5884 DeclarationName Name = Data->Method->getDeclName();
5885
5886 // FIXME: Do we care about other names here too?
5887 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005888 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005889 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5890 CanQualType CT = Data->S->Context.getCanonicalType(T);
5891
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005892 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005893 }
5894
5895 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005896 !Path.Decls.empty();
5897 Path.Decls = Path.Decls.slice(1)) {
5898 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005899 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5900 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005901 return true;
5902 }
5903 }
5904
5905 return false;
5906}
5907
David Blaikie7e414262012-10-17 00:47:58 +00005908namespace {
5909 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5910}
5911/// \brief Report an error regarding overriding, along with any relevant
5912/// overriden methods.
5913///
5914/// \param DiagID the primary error to report.
5915/// \param MD the overriding method.
5916/// \param OEK which overrides to include as notes.
5917static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5918 OverrideErrorKind OEK = OEK_All) {
5919 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5920 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5921 E = MD->end_overridden_methods();
5922 I != E; ++I) {
5923 // This check (& the OEK parameter) could be replaced by a predicate, but
5924 // without lambdas that would be overkill. This is still nicer than writing
5925 // out the diag loop 3 times.
5926 if ((OEK == OEK_All) ||
5927 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5928 (OEK == OEK_Deleted && (*I)->isDeleted()))
5929 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5930 }
5931}
5932
Sebastian Redld5b24532009-11-18 21:51:29 +00005933/// AddOverriddenMethods - See if a method overrides any in the base classes,
5934/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005935bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00005936 // Look for virtual methods in base classes that this method might override.
5937 CXXBasePaths Paths;
5938 FindOverriddenMethodData Data;
5939 Data.Method = MD;
5940 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00005941 bool hasDeletedOverridenMethods = false;
5942 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005943 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00005944 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5945 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5946 E = Paths.found_decls_end(); I != E; ++I) {
5947 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00005948 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00005949 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00005950 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00005951 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00005952 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00005953 hasDeletedOverridenMethods |= OldMD->isDeleted();
5954 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005955 AddedAny = true;
5956 }
Sebastian Redld5b24532009-11-18 21:51:29 +00005957 }
5958 }
5959 }
David Blaikie7e414262012-10-17 00:47:58 +00005960
5961 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5962 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5963 }
5964 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5965 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5966 }
5967
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005968 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00005969}
5970
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005971namespace {
5972 // Struct for holding all of the extra arguments needed by
5973 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5974 struct ActOnFDArgs {
5975 Scope *S;
5976 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005977 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005978 bool AddToScope;
5979 };
5980}
5981
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005982namespace {
5983
5984// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005985// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005986class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5987 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005988 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5989 CXXRecordDecl *Parent)
5990 : Context(Context), OriginalFD(TypoFD),
5991 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005992
Craig Toppere14c0f82014-03-12 04:55:44 +00005993 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005994 if (candidate.getEditDistance() == 0)
5995 return false;
5996
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005997 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005998 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5999 CDeclEnd = candidate.end();
6000 CDecl != CDeclEnd; ++CDecl) {
6001 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6002
6003 if (FD && !FD->hasBody() &&
6004 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6005 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6006 CXXRecordDecl *Parent = MD->getParent();
6007 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6008 return true;
6009 } else if (!ExpectedParent) {
6010 return true;
6011 }
6012 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006013 }
6014
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006015 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006016 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006017
6018 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006019 ASTContext &Context;
6020 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006021 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006022};
6023
6024}
6025
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006026/// \brief Generate diagnostics for an invalid function redeclaration.
6027///
6028/// This routine handles generating the diagnostic messages for an invalid
6029/// function redeclaration, including finding possible similar declarations
6030/// or performing typo correction if there are no previous declarations with
6031/// the same name.
6032///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006033/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006034/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006035static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006036 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006037 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006038 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006039 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006040 SmallVector<unsigned, 1> MismatchedParams;
6041 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006042 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006043 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006044 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6045 : diag::err_member_decl_does_not_match;
6046 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6047 IsLocalFriend ? Sema::LookupLocalFriendName
6048 : Sema::LookupOrdinaryName,
6049 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006050
6051 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006052 if (IsLocalFriend)
6053 SemaRef.LookupName(Prev, S);
6054 else
6055 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006056 assert(!Prev.isAmbiguous() &&
6057 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006058 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006059 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6060 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006061 if (!Prev.empty()) {
6062 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6063 Func != FuncEnd; ++Func) {
6064 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006065 if (FD &&
6066 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006067 // Add 1 to the index so that 0 can mean the mismatch didn't
6068 // involve a parameter
6069 unsigned ParamNum =
6070 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6071 NearMatches.push_back(std::make_pair(FD, ParamNum));
6072 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006073 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006074 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006075 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006076 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6077 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6078 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006079 // Set up everything for the call to ActOnFunctionDeclarator
6080 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6081 ExtraArgs.D.getIdentifierLoc());
6082 Previous.clear();
6083 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006084 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6085 CDeclEnd = Correction.end();
6086 CDecl != CDeclEnd; ++CDecl) {
6087 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006088 if (FD && !FD->hasBody() &&
6089 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006090 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006091 }
6092 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006093 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006094
6095 NamedDecl *Result;
6096 // Retry building the function declaration with the new previous
6097 // declarations, and with errors suppressed.
6098 {
6099 // Trap errors.
6100 Sema::SFINAETrap Trap(SemaRef);
6101
6102 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6103 // pieces need to verify the typo-corrected C++ declaration and hopefully
6104 // eliminate the need for the parameter pack ExtraArgs.
6105 Result = SemaRef.ActOnFunctionDeclarator(
6106 ExtraArgs.S, ExtraArgs.D,
6107 Correction.getCorrectionDecl()->getDeclContext(),
6108 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6109 ExtraArgs.AddToScope);
6110
6111 if (Trap.hasErrorOccurred())
6112 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006113 }
Richard Smithf9b15102013-08-17 00:46:16 +00006114
6115 if (Result) {
6116 // Determine which correction we picked.
6117 Decl *Canonical = Result->getCanonicalDecl();
6118 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6119 I != E; ++I)
6120 if ((*I)->getCanonicalDecl() == Canonical)
6121 Correction.setCorrectionDecl(*I);
6122
6123 SemaRef.diagnoseTypo(
6124 Correction,
6125 SemaRef.PDiag(IsLocalFriend
6126 ? diag::err_no_matching_local_friend_suggest
6127 : diag::err_member_decl_does_not_match_suggest)
6128 << Name << NewDC << IsDefinition);
6129 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006130 }
Richard Smithf9b15102013-08-17 00:46:16 +00006131
6132 // Pretend the typo correction never occurred
6133 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6134 ExtraArgs.D.getIdentifierLoc());
6135 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6136 Previous.clear();
6137 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006138 }
6139
Richard Smithf9b15102013-08-17 00:46:16 +00006140 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6141 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006142
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006143 bool NewFDisConst = false;
6144 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006145 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006146
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006147 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006148 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6149 NearMatch != NearMatchEnd; ++NearMatch) {
6150 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006151 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6152 bool FDisConst = MD && MD->isConst();
6153 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006154
Richard Smith541b38b2013-09-20 01:15:31 +00006155 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006156 if (unsigned Idx = NearMatch->second) {
6157 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006158 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6159 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006160 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6161 : diag::note_local_decl_close_param_match)
6162 << Idx << FDParam->getType()
6163 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006164 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006165 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006166 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006167 } else
Richard Smith114394f2013-08-09 04:35:01 +00006168 SemaRef.Diag(FD->getLocation(),
6169 IsMember ? diag::note_member_def_close_match
6170 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006171 }
Richard Smithf9b15102013-08-17 00:46:16 +00006172 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006173}
6174
David Blaikie30d15442011-10-19 22:56:21 +00006175static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6176 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006177 switch (D.getDeclSpec().getStorageClassSpec()) {
6178 default: llvm_unreachable("Unknown storage class!");
6179 case DeclSpec::SCS_auto:
6180 case DeclSpec::SCS_register:
6181 case DeclSpec::SCS_mutable:
6182 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6183 diag::err_typecheck_sclass_func);
6184 D.setInvalidType();
6185 break;
6186 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006187 case DeclSpec::SCS_extern:
6188 if (D.getDeclSpec().isExternInLinkageSpec())
6189 return SC_None;
6190 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006191 case DeclSpec::SCS_static: {
6192 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6193 // C99 6.7.1p5:
6194 // The declaration of an identifier for a function that has
6195 // block scope shall have no explicit storage-class specifier
6196 // other than extern
6197 // See also (C++ [dcl.stc]p4).
6198 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6199 diag::err_static_block_func);
6200 break;
6201 } else
6202 return SC_Static;
6203 }
6204 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6205 }
6206
6207 // No explicit storage class has already been returned
6208 return SC_None;
6209}
6210
6211static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6212 DeclContext *DC, QualType &R,
6213 TypeSourceInfo *TInfo,
6214 FunctionDecl::StorageClass SC,
6215 bool &IsVirtualOkay) {
6216 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6217 DeclarationName Name = NameInfo.getName();
6218
6219 FunctionDecl *NewFD = 0;
6220 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006221
David Blaikiebbafb8a2012-03-11 07:00:24 +00006222 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006223 // Determine whether the function was written with a
6224 // prototype. This true when:
6225 // - there is a prototype in the declarator, or
6226 // - the type R of the function is some kind of typedef or other reference
6227 // to a type name (which eventually refers to a function type).
6228 bool HasPrototype =
6229 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6230 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6231
David Blaikie30d15442011-10-19 22:56:21 +00006232 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006233 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006234 TInfo, SC, isInline,
6235 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006236 if (D.isInvalidType())
6237 NewFD->setInvalidDecl();
6238
6239 // Set the lexical context.
6240 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6241
6242 return NewFD;
6243 }
6244
6245 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6246 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6247
6248 // Check that the return type is not an abstract class type.
6249 // For record types, this is done by the AbstractClassUsageDiagnoser once
6250 // the class has been completely parsed.
6251 if (!DC->isRecord() &&
Alp Toker314cc812014-01-25 16:55:45 +00006252 SemaRef.RequireNonAbstractType(
6253 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6254 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006255 D.setInvalidType();
6256
6257 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6258 // This is a C++ constructor declaration.
6259 assert(DC->isRecord() &&
6260 "Constructors can only be declared in a member context");
6261
6262 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6263 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006264 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006265 R, TInfo, isExplicit, isInline,
6266 /*isImplicitlyDeclared=*/false,
6267 isConstexpr);
6268
6269 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6270 // This is a C++ destructor declaration.
6271 if (DC->isRecord()) {
6272 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6273 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6274 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6275 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006276 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006277 NameInfo, R, TInfo, isInline,
6278 /*isImplicitlyDeclared=*/false);
6279
6280 // If the class is complete, then we now create the implicit exception
6281 // specification. If the class is incomplete or dependent, we can't do
6282 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006283 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006284 Record->getDefinition() && !Record->isBeingDefined() &&
6285 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6286 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6287 }
6288
6289 IsVirtualOkay = true;
6290 return NewDD;
6291
6292 } else {
6293 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6294 D.setInvalidType();
6295
6296 // Create a FunctionDecl to satisfy the function definition parsing
6297 // code path.
6298 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006299 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006300 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006301 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006302 /*hasPrototype=*/true, isConstexpr);
6303 }
6304
6305 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6306 if (!DC->isRecord()) {
6307 SemaRef.Diag(D.getIdentifierLoc(),
6308 diag::err_conv_function_not_member);
6309 return 0;
6310 }
6311
6312 SemaRef.CheckConversionDeclarator(D, R, SC);
6313 IsVirtualOkay = true;
6314 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006315 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006316 R, TInfo, isInline, isExplicit,
6317 isConstexpr, SourceLocation());
6318
6319 } else if (DC->isRecord()) {
6320 // If the name of the function is the same as the name of the record,
6321 // then this must be an invalid constructor that has a return type.
6322 // (The parser checks for a return type and makes the declarator a
6323 // constructor if it has no return type).
6324 if (Name.getAsIdentifierInfo() &&
6325 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6326 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6327 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6328 << SourceRange(D.getIdentifierLoc());
6329 return 0;
6330 }
6331
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006332 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006333 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6334 cast<CXXRecordDecl>(DC),
6335 D.getLocStart(), NameInfo, R,
6336 TInfo, SC, isInline,
6337 isConstexpr, SourceLocation());
6338 IsVirtualOkay = !Ret->isStatic();
6339 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006340 } else {
6341 // Determine whether the function was written with a
6342 // prototype. This true when:
6343 // - we're in C++ (where every function has a prototype),
6344 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006345 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006346 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006347 true/*HasPrototype*/, isConstexpr);
6348 }
6349}
6350
Matt Arsenaultefb38192013-07-23 01:23:36 +00006351enum OpenCLParamType {
6352 ValidKernelParam,
6353 PtrPtrKernelParam,
6354 PtrKernelParam,
6355 InvalidKernelParam,
6356 RecordKernelParam
6357};
6358
6359static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6360 if (PT->isPointerType()) {
6361 QualType PointeeType = PT->getPointeeType();
6362 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6363 }
6364
6365 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6366 // be used as builtin types.
6367
6368 if (PT->isImageType())
6369 return PtrKernelParam;
6370
6371 if (PT->isBooleanType())
6372 return InvalidKernelParam;
6373
6374 if (PT->isEventT())
6375 return InvalidKernelParam;
6376
6377 if (PT->isHalfType())
6378 return InvalidKernelParam;
6379
6380 if (PT->isRecordType())
6381 return RecordKernelParam;
6382
6383 return ValidKernelParam;
6384}
6385
6386static void checkIsValidOpenCLKernelParameter(
6387 Sema &S,
6388 Declarator &D,
6389 ParmVarDecl *Param,
6390 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6391 QualType PT = Param->getType();
6392
6393 // Cache the valid types we encounter to avoid rechecking structs that are
6394 // used again
6395 if (ValidTypes.count(PT.getTypePtr()))
6396 return;
6397
6398 switch (getOpenCLKernelParameterType(PT)) {
6399 case PtrPtrKernelParam:
6400 // OpenCL v1.2 s6.9.a:
6401 // A kernel function argument cannot be declared as a
6402 // pointer to a pointer type.
6403 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6404 D.setInvalidType();
6405 return;
6406
6407 // OpenCL v1.2 s6.9.k:
6408 // Arguments to kernel functions in a program cannot be declared with the
6409 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6410 // uintptr_t or a struct and/or union that contain fields declared to be
6411 // one of these built-in scalar types.
6412
6413 case InvalidKernelParam:
6414 // OpenCL v1.2 s6.8 n:
6415 // A kernel function argument cannot be declared
6416 // of event_t type.
6417 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6418 D.setInvalidType();
6419 return;
6420
6421 case PtrKernelParam:
6422 case ValidKernelParam:
6423 ValidTypes.insert(PT.getTypePtr());
6424 return;
6425
6426 case RecordKernelParam:
6427 break;
6428 }
6429
6430 // Track nested structs we will inspect
6431 SmallVector<const Decl *, 4> VisitStack;
6432
6433 // Track where we are in the nested structs. Items will migrate from
6434 // VisitStack to HistoryStack as we do the DFS for bad field.
6435 SmallVector<const FieldDecl *, 4> HistoryStack;
6436 HistoryStack.push_back((const FieldDecl *) 0);
6437
6438 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6439 VisitStack.push_back(PD);
6440
6441 assert(VisitStack.back() && "First decl null?");
6442
6443 do {
6444 const Decl *Next = VisitStack.pop_back_val();
6445 if (!Next) {
6446 assert(!HistoryStack.empty());
6447 // Found a marker, we have gone up a level
6448 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6449 ValidTypes.insert(Hist->getType().getTypePtr());
6450
6451 continue;
6452 }
6453
6454 // Adds everything except the original parameter declaration (which is not a
6455 // field itself) to the history stack.
6456 const RecordDecl *RD;
6457 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6458 HistoryStack.push_back(Field);
6459 RD = Field->getType()->castAs<RecordType>()->getDecl();
6460 } else {
6461 RD = cast<RecordDecl>(Next);
6462 }
6463
6464 // Add a null marker so we know when we've gone back up a level
6465 VisitStack.push_back((const Decl *) 0);
6466
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006467 for (const auto *FD : RD->fields()) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006468 QualType QT = FD->getType();
6469
6470 if (ValidTypes.count(QT.getTypePtr()))
6471 continue;
6472
6473 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6474 if (ParamType == ValidKernelParam)
6475 continue;
6476
6477 if (ParamType == RecordKernelParam) {
6478 VisitStack.push_back(FD);
6479 continue;
6480 }
6481
6482 // OpenCL v1.2 s6.9.p:
6483 // Arguments to kernel functions that are declared to be a struct or union
6484 // do not allow OpenCL objects to be passed as elements of the struct or
6485 // union.
6486 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6487 S.Diag(Param->getLocation(),
6488 diag::err_record_with_pointers_kernel_param)
6489 << PT->isUnionType()
6490 << PT;
6491 } else {
6492 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6493 }
6494
6495 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6496 << PD->getDeclName();
6497
6498 // We have an error, now let's go back up through history and show where
6499 // the offending field came from
6500 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6501 E = HistoryStack.end(); I != E; ++I) {
6502 const FieldDecl *OuterField = *I;
6503 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6504 << OuterField->getType();
6505 }
6506
6507 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6508 << QT->isPointerType()
6509 << QT;
6510 D.setInvalidType();
6511 return;
6512 }
6513 } while (!VisitStack.empty());
6514}
6515
Mike Stump11289f42009-09-09 15:08:12 +00006516NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006517Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006518 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006519 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006520 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006521 QualType R = TInfo->getType();
6522
Zhongxing Xubece5d62009-01-16 01:13:29 +00006523 assert(R.getTypePtr()->isFunctionType());
6524
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006525 // TODO: consider using NameInfo for diagnostic.
6526 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6527 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006528 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006529
Richard Smithb4a9e862013-04-12 22:46:28 +00006530 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6531 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6532 diag::err_invalid_thread)
6533 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006534
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006535 if (D.isFirstDeclarationOfMember())
6536 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006537
Douglas Gregor513e63c2010-12-10 19:28:19 +00006538 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006539 FunctionTemplateDecl *FunctionTemplate = 0;
6540 bool isExplicitSpecialization = false;
6541 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006542
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006543 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006544 bool HasExplicitTemplateArgs = false;
6545 TemplateArgumentListInfo TemplateArgs;
6546
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006547 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006548
Richard Smith541b38b2013-09-20 01:15:31 +00006549 DeclContext *OriginalDC = DC;
6550 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6551
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006552 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6553 isVirtualOkay);
6554 if (!NewFD) return 0;
6555
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006556 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6557 NewFD->setTopLevelDeclInObjCContainer();
6558
Richard Smith541b38b2013-09-20 01:15:31 +00006559 // Set the lexical context. If this is a function-scope declaration, or has a
6560 // C++ scope specifier, or is the object of a friend declaration, the lexical
6561 // context will be different from the semantic context.
6562 NewFD->setLexicalDeclContext(CurContext);
6563
6564 if (IsLocalExternDecl)
6565 NewFD->setLocalExternDecl();
6566
David Blaikiebbafb8a2012-03-11 07:00:24 +00006567 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006568 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006569 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6570 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006571 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006572 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006573 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006574 // C++ [class.friend]p5
6575 // A function can be defined in a friend declaration of a
6576 // class . . . . Such a function is implicitly inline.
6577 NewFD->setImplicitlyInline();
6578 }
6579
John McCalldb632ac2012-09-25 07:32:39 +00006580 // If this is a method defined in an __interface, and is not a constructor
6581 // or an overloaded operator, then set the pure flag (isVirtual will already
6582 // return true).
6583 if (const CXXRecordDecl *Parent =
6584 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6585 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006586 NewFD->setPure(true);
6587 }
6588
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006589 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006590 isExplicitSpecialization = false;
6591 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006592 if (D.isInvalidType())
6593 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006594
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006595 // Match up the template parameter lists with the scope specifier, then
6596 // determine whether we have a template or a template specialization.
6597 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006598 if (TemplateParameterList *TemplateParams =
6599 MatchTemplateParametersToScopeSpecifier(
6600 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6601 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6602 isExplicitSpecialization, Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006603 if (TemplateParams->size() > 0) {
6604 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006605
Abramo Bagnara60804e12011-03-18 15:16:37 +00006606 // Check that we can declare a template here.
6607 if (CheckTemplateDeclScope(S, TemplateParams))
6608 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006609
Abramo Bagnara60804e12011-03-18 15:16:37 +00006610 // A destructor cannot be a template.
6611 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6612 Diag(NewFD->getLocation(), diag::err_destructor_template);
6613 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006614 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006615
6616 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006617 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006618 // now that we know what the current instantiation is.
6619 if (DC->isDependentContext()) {
6620 ContextRAII SavedContext(*this, DC);
6621 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6622 Invalid = true;
6623 }
6624
John McCall1f0479e2010-03-24 08:27:58 +00006625
Abramo Bagnara60804e12011-03-18 15:16:37 +00006626 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6627 NewFD->getLocation(),
6628 Name, TemplateParams,
6629 NewFD);
6630 FunctionTemplate->setLexicalDeclContext(CurContext);
6631 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6632
6633 // For source fidelity, store the other template param lists.
6634 if (TemplateParamLists.size() > 1) {
6635 NewFD->setTemplateParameterListsInfo(Context,
6636 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006637 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006638 }
6639 } else {
6640 // This is a function template specialization.
6641 isFunctionTemplateSpecialization = true;
6642 // For source fidelity, store all the template param lists.
6643 NewFD->setTemplateParameterListsInfo(Context,
6644 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006645 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006646
6647 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6648 if (isFriend) {
6649 // We want to remove the "template<>", found here.
6650 SourceRange RemoveRange = TemplateParams->getSourceRange();
6651
6652 // If we remove the template<> and the name is not a
6653 // template-id, we're actually silently creating a problem:
6654 // the friend declaration will refer to an untemplated decl,
6655 // and clearly the user wants a template specialization. So
6656 // we need to insert '<>' after the name.
6657 SourceLocation InsertLoc;
6658 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6659 InsertLoc = D.getName().getSourceRange().getEnd();
6660 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6661 }
6662
6663 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6664 << Name << RemoveRange
6665 << FixItHint::CreateRemoval(RemoveRange)
6666 << FixItHint::CreateInsertion(InsertLoc, "<>");
6667 }
6668 }
6669 }
6670 else {
6671 // All template param lists were matched against the scope specifier:
6672 // this is NOT (an explicit specialization of) a template.
6673 if (TemplateParamLists.size() > 0)
6674 // For source fidelity, store all the template param lists.
6675 NewFD->setTemplateParameterListsInfo(Context,
6676 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006677 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006678 }
6679
6680 if (Invalid) {
6681 NewFD->setInvalidDecl();
6682 if (FunctionTemplate)
6683 FunctionTemplate->setInvalidDecl();
6684 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006685
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006686 // C++ [dcl.fct.spec]p5:
6687 // The virtual specifier shall only be used in declarations of
6688 // nonstatic class member functions that appear within a
6689 // member-specification of a class declaration; see 10.3.
6690 //
6691 if (isVirtual && !NewFD->isInvalidDecl()) {
6692 if (!isVirtualOkay) {
6693 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6694 diag::err_virtual_non_function);
6695 } else if (!CurContext->isRecord()) {
6696 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006697 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6698 diag::err_virtual_out_of_class)
6699 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6700 } else if (NewFD->getDescribedFunctionTemplate()) {
6701 // C++ [temp.mem]p3:
6702 // A member function template shall not be virtual.
6703 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6704 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006705 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6706 } else {
6707 // Okay: Add virtual to the method.
6708 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006709 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006710
6711 if (getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00006712 NewFD->getReturnType()->isUndeducedType())
Richard Smith2a7d4812013-05-04 07:00:32 +00006713 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006714 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006715
Richard Smithc1564702013-11-15 02:58:23 +00006716 if (getLangOpts().CPlusPlus1y &&
6717 (NewFD->isDependentContext() ||
6718 (isFriend && CurContext->isDependentContext())) &&
Alp Toker314cc812014-01-25 16:55:45 +00006719 NewFD->getReturnType()->isUndeducedType()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00006720 // If the function template is referenced directly (for instance, as a
6721 // member of the current instantiation), pretend it has a dependent type.
6722 // This is not really justified by the standard, but is the only sane
6723 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006724 // FIXME: For a friend function, we have not marked the function as being
6725 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006726 const FunctionProtoType *FPT =
6727 NewFD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006728 QualType Result =
6729 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00006730 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smithc58f38f2013-08-14 20:16:31 +00006731 FPT->getExtProtoInfo()));
6732 }
6733
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006734 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006735 // The inline specifier shall not appear on a block scope function
6736 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006737 if (isInline && !NewFD->isInvalidDecl()) {
6738 if (CurContext->isFunctionOrMethod()) {
6739 // 'inline' is not allowed on block scope function declaration.
6740 Diag(D.getDeclSpec().getInlineSpecLoc(),
6741 diag::err_inline_declaration_block_scope) << Name
6742 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6743 }
6744 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006745
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006746 // C++ [dcl.fct.spec]p6:
6747 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006748 // constructor or conversion function within its class definition;
6749 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006750 if (isExplicit && !NewFD->isInvalidDecl()) {
6751 if (!CurContext->isRecord()) {
6752 // 'explicit' was specified outside of the class.
6753 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6754 diag::err_explicit_out_of_class)
6755 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6756 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6757 !isa<CXXConversionDecl>(NewFD)) {
6758 // 'explicit' was specified on a function that wasn't a constructor
6759 // or conversion function.
6760 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6761 diag::err_explicit_non_ctor_or_conv_function)
6762 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6763 }
6764 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006765
Richard Smitha77a0a62011-08-15 21:04:07 +00006766 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006767 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006768 // are implicitly inline.
6769 NewFD->setImplicitlyInline();
6770
Richard Smith574f4f62013-01-14 05:37:29 +00006771 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006772 // be either constructors or to return a literal type. Therefore,
6773 // destructors cannot be declared constexpr.
6774 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006775 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006776 }
6777
Douglas Gregor26701a42011-09-09 02:06:17 +00006778 // If __module_private__ was specified, mark the function accordingly.
6779 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006780 if (isFunctionTemplateSpecialization) {
6781 SourceLocation ModulePrivateLoc
6782 = D.getDeclSpec().getModulePrivateSpecLoc();
6783 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6784 << 0
6785 << FixItHint::CreateRemoval(ModulePrivateLoc);
6786 } else {
6787 NewFD->setModulePrivate();
6788 if (FunctionTemplate)
6789 FunctionTemplate->setModulePrivate();
6790 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006791 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006792
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006793 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006794 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006795 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006796 FunctionTemplate->setAccess(AS_public);
6797 }
Richard Smith64017682013-07-17 23:53:16 +00006798 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006799 NewFD->setAccess(AS_public);
6800 }
6801
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006802 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithb63b6ee2014-01-22 01:43:19 +00006803 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6804 // definition kind to FDK_Definition.
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006805 switch (D.getFunctionDefinitionKind()) {
6806 case FDK_Declaration:
6807 case FDK_Definition:
6808 break;
6809
6810 case FDK_Defaulted:
6811 NewFD->setDefaulted();
6812 break;
6813
6814 case FDK_Deleted:
6815 NewFD->setDeletedAsWritten();
6816 break;
6817 }
6818
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006819 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6820 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006821 // C++ [class.mfct]p2:
6822 // A member function may be defined (8.4) in its class definition, in
6823 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006824 NewFD->setImplicitlyInline();
6825 }
6826
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006827 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6828 !CurContext->isRecord()) {
6829 // C++ [class.static]p1:
6830 // A data or function member of a class may be declared static
6831 // in a class definition, in which case it is a static member of
6832 // the class.
6833
6834 // Complain about the 'static' specifier if it's on an out-of-line
6835 // member function definition.
6836 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6837 diag::err_static_out_of_line)
6838 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6839 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006840
6841 // C++11 [except.spec]p15:
6842 // A deallocation function with no exception-specification is treated
6843 // as if it were specified with noexcept(true).
6844 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6845 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6846 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006847 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006848 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6849 EPI.ExceptionSpecType = EST_BasicNoexcept;
Alp Toker314cc812014-01-25 16:55:45 +00006850 NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006851 FPT->getParamTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006852 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006853 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006854
6855 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006856 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00006857 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006858 isExplicitSpecialization ||
6859 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006860
Zhongxing Xubece5d62009-01-16 01:13:29 +00006861 // Handle GNU asm-label extension (encoded as an attribute).
6862 if (Expr *E = (Expr*) D.getAsmLabel()) {
6863 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006864 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006865 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00006866 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00006867 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6868 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6869 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6870 if (I != ExtnameUndeclaredIdentifiers.end()) {
6871 NewFD->addAttr(I->second);
6872 ExtnameUndeclaredIdentifiers.erase(I);
6873 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006874 }
6875
Chris Lattner9af40c12009-04-25 06:12:16 +00006876 // Copy the parameter declarations from the declarator D to the function
6877 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006878 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006879 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006880 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006881
Zhongxing Xubece5d62009-01-16 01:13:29 +00006882 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6883 // function that takes no arguments, not a function that takes a
6884 // single void argument.
6885 // We let through "const void" here because Sema::GetTypeForDeclarator
6886 // already checks for that case.
Alp Tokerc5350722014-02-26 22:27:52 +00006887 if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6888 FTI.Params[0].Param &&
6889 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00006890 // Empty arg list, don't push any params.
Alp Tokerc5350722014-02-26 22:27:52 +00006891 } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) {
6892 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
6893 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006894 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6895 Param->setDeclContext(NewFD);
6896 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00006897
6898 if (Param->isInvalidDecl())
6899 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006900 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006901 }
Mike Stump11289f42009-09-09 15:08:12 +00006902
John McCall9dd450b2009-09-21 23:43:11 +00006903 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00006904 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00006905 // following example, we'll need to synthesize (unnamed)
6906 // parameters for use in the declaration.
6907 //
6908 // @code
6909 // typedef void fn(int);
6910 // fn f;
6911 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00006912
Chris Lattner47c0d002009-04-25 06:03:53 +00006913 // Synthesize a parameter for each argument type.
Alp Toker9cacbab2014-01-20 20:26:09 +00006914 for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(),
6915 AE = FT->param_type_end();
6916 AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00006917 ParmVarDecl *Param =
6918 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00006919 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00006920 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006921 }
Chris Lattner49303b22009-04-25 18:38:18 +00006922 } else {
6923 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6924 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00006925 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00006926
Chris Lattner9af40c12009-04-25 06:12:16 +00006927 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00006928 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00006929
James Molloy6f8780b2012-02-29 10:24:19 +00006930 // Find all anonymous symbols defined during the declaration of this function
6931 // and add to NewFD. This lets us track decls such 'enum Y' in:
6932 //
6933 // void f(enum Y {AA} x) {}
6934 //
6935 // which would otherwise incorrectly end up in the translation unit scope.
6936 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6937 DeclsInPrototypeScope.clear();
6938
Richard Smithdebc59d2013-01-30 05:45:05 +00006939 if (D.getDeclSpec().isNoreturnSpecified())
6940 NewFD->addAttr(
6941 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
Aaron Ballman36a53502014-01-16 13:03:14 +00006942 Context, 0));
Richard Smithdebc59d2013-01-30 05:45:05 +00006943
Richard Smith84208dc2012-03-13 05:56:40 +00006944 // Functions returning a variably modified type violate C99 6.7.5.2p2
6945 // because all functions have linkage.
6946 if (!NewFD->isInvalidDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +00006947 NewFD->getReturnType()->isVariablyModifiedType()) {
Richard Smith84208dc2012-03-13 05:56:40 +00006948 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6949 NewFD->setInvalidDecl();
6950 }
6951
Rafael Espindolac67f2232012-05-10 02:50:16 +00006952 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00006953 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00006954
Alp Toker314cc812014-01-25 16:55:45 +00006955 QualType RetType = NewFD->getReturnType();
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006956 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6957 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6958 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6959 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006960 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
David Blaikie080a61c2014-02-09 07:24:41 +00006961 // Attach WarnUnusedResult to functions returning types with that attribute.
6962 // Don't apply the attribute to that type's own non-static member functions
6963 // (to avoid warning on things like assignment operators)
6964 if (!MD || MD->getParent() != Ret)
Aaron Ballman36a53502014-01-16 13:03:14 +00006965 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006966 }
6967
Joey Gouly16cb99d2014-01-06 11:26:18 +00006968 if (getLangOpts().OpenCL) {
6969 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
6970 // type declaration will generate a compilation error.
6971 unsigned AddressSpace = RetType.getAddressSpace();
6972 if (AddressSpace == LangAS::opencl_local ||
6973 AddressSpace == LangAS::opencl_global ||
6974 AddressSpace == LangAS::opencl_constant) {
6975 Diag(NewFD->getLocation(),
6976 diag::err_opencl_return_value_with_address_space);
6977 NewFD->setInvalidDecl();
6978 }
6979 }
6980
David Blaikiebbafb8a2012-03-11 07:00:24 +00006981 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006982 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00006983 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00006984 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6985 CheckMain(NewFD, D.getDeclSpec());
6986
David Majnemerc729b0b2013-09-16 22:44:20 +00006987 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6988 CheckMSVCRTEntryPoint(NewFD);
6989
David Majnemer027f9c42013-07-06 02:13:46 +00006990 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00006991 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6992 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00006993 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00006994 // Make graceful recovery from an invalid redeclaration.
6995 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006996 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006997 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
6998 "previous declaration set still overloaded");
6999 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007000 // C++11 [replacement.functions]p3:
7001 // The program's definitions shall not be specified as inline.
7002 //
7003 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7004 //
7005 // Suppress the diagnostic if the function is __attribute__((used)), since
7006 // that forces an external definition to be emitted.
7007 if (D.getDeclSpec().isInlineSpecified() &&
7008 NewFD->isReplaceableGlobalAllocationFunction() &&
7009 !NewFD->hasAttr<UsedAttr>())
7010 Diag(D.getDeclSpec().getInlineSpecLoc(),
7011 diag::ext_operator_new_delete_declared_inline)
7012 << NewFD->getDeclName();
7013
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007014 // If the declarator is a template-id, translate the parser's template
7015 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007016 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7017 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7018 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7019 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007020 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007021 TemplateId->NumArgs);
7022 translateTemplateArguments(TemplateArgsPtr,
7023 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007024
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007025 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007026
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007027 if (NewFD->isInvalidDecl()) {
7028 HasExplicitTemplateArgs = false;
7029 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007030 // Function template with explicit template arguments.
7031 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7032 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7033
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007034 HasExplicitTemplateArgs = false;
7035 } else if (!isFunctionTemplateSpecialization &&
7036 !D.getDeclSpec().isFriendSpecified()) {
7037 // We have encountered something that the user meant to be a
7038 // specialization (because it has explicitly-specified template
7039 // arguments) but that was not introduced with a "template<>" (or had
7040 // too few of them).
Larisse Voufo39a1e502013-08-06 01:03:05 +00007041 // FIXME: Differentiate between attempts for explicit instantiations
7042 // (starting with "template") and the rest.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007043 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7044 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7045 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007046 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00007047 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007048 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00007049 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007050 // "friend void foo<>(int);" is an implicit specialization decl.
7051 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007052 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007053 } else if (isFriend && isFunctionTemplateSpecialization) {
7054 // This combination is only possible in a recovery case; the user
7055 // wrote something like:
7056 // template <> friend void foo(int);
7057 // which we're recovering from as if the user had written:
7058 // friend void foo<>(int);
7059 // Go ahead and fake up a template id.
7060 HasExplicitTemplateArgs = true;
7061 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7062 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007063 }
John McCallf7cfb222010-10-13 05:45:15 +00007064
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007065 // If it's a friend (and only if it's a friend), it's possible
7066 // that either the specialized function type or the specialized
7067 // template is dependent, and therefore matching will fail. In
7068 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007069 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007070 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007071 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7072 TemplateSpecializationType::anyDependentTemplateArguments(
7073 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7074 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007075 assert(HasExplicitTemplateArgs &&
7076 "friend function specialization without template args");
7077 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7078 Previous))
7079 NewFD->setInvalidDecl();
7080 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007081 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007082 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007083 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007084 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007085 diag::ext_function_specialization_in_class :
7086 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007087 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007088 } else if (CheckFunctionTemplateSpecialization(NewFD,
7089 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7090 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007091 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007092
7093 // C++ [dcl.stc]p1:
7094 // A storage-class-specifier shall not be specified in an explicit
7095 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007096 FunctionTemplateSpecializationInfo *Info =
7097 NewFD->getTemplateSpecializationInfo();
7098 if (Info && SC != SC_None) {
7099 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007100 Diag(NewFD->getLocation(),
7101 diag::err_explicit_specialization_inconsistent_storage_class)
7102 << SC
7103 << FixItHint::CreateRemoval(
7104 D.getDeclSpec().getStorageClassSpecLoc());
7105
7106 else
7107 Diag(NewFD->getLocation(),
7108 diag::ext_explicit_specialization_storage_class)
7109 << FixItHint::CreateRemoval(
7110 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007111 }
7112
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007113 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7114 if (CheckMemberSpecialization(NewFD, Previous))
7115 NewFD->setInvalidDecl();
7116 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007117
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007118 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007119 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007120 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7121 CheckMain(NewFD, D.getDeclSpec());
7122
David Majnemerc729b0b2013-09-16 22:44:20 +00007123 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7124 CheckMSVCRTEntryPoint(NewFD);
7125
Nico Weber7607fce2013-12-21 00:49:51 +00007126 if (!NewFD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007127 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7128 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007129 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007130
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007131 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007132 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7133 "previous declaration set still overloaded");
7134
7135 NamedDecl *PrincipalDecl = (FunctionTemplate
7136 ? cast<NamedDecl>(FunctionTemplate)
7137 : NewFD);
7138
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007139 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007140 AccessSpecifier Access = AS_public;
7141 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007142 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007143
7144 NewFD->setAccess(Access);
7145 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007146 }
7147
7148 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7149 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7150 PrincipalDecl->setNonMemberOperator();
7151
7152 // If we have a function template, check the template parameter
7153 // list. This will check and merge default template arguments.
7154 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007155 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007156 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007157 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00007158 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007159 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007160 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007161 ? TPC_FriendFunctionTemplateDefinition
7162 : TPC_FriendFunctionTemplate)
7163 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007164 DC && DC->isRecord() &&
7165 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007166 ? TPC_ClassTemplateMember
7167 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007168 }
7169
7170 if (NewFD->isInvalidDecl()) {
7171 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007172 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007173 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007174 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007175 // Fake up an access specifier if it's supposed to be a class member.
7176 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7177 NewFD->setAccess(AS_public);
7178
7179 // Qualified decls generally require a previous declaration.
7180 if (D.getCXXScopeSpec().isSet()) {
7181 // ...with the major exception of templated-scope or
7182 // dependent-scope friend declarations.
7183
7184 // TODO: we currently also suppress this check in dependent
7185 // contexts because (1) the parameter depth will be off when
7186 // matching friend templates and (2) we might actually be
7187 // selecting a friend based on a dependent factor. But there
7188 // are situations where these conditions don't apply and we
7189 // can actually do this check immediately.
7190 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007191 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007192 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7193 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007194 // ignore these
7195 } else {
7196 // The user tried to provide an out-of-line definition for a
7197 // function that is a member of a class or namespace, but there
7198 // was no such member function declared (C++ [class.mfct]p2,
7199 // C++ [namespace.memdef]p2). For example:
7200 //
7201 // class X {
7202 // void f() const;
7203 // };
7204 //
7205 // void X::f() { } // ill-formed
7206 //
7207 // Complain about this problem, and attempt to suggest close
7208 // matches (e.g., those that differ only in cv-qualifiers and
7209 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007210
Richard Smith114394f2013-08-09 04:35:01 +00007211 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7212 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007213 AddToScope = ExtraArgs.AddToScope;
7214 return Result;
7215 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007216 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007217
7218 // Unqualified local friend declarations are required to resolve
7219 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007220 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007221 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7222 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007223 AddToScope = ExtraArgs.AddToScope;
7224 return Result;
7225 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007226 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007227
Richard Smitha2302242013-12-05 07:51:02 +00007228 } else if (!D.isFunctionDefinition() &&
7229 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007230 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007231 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007232 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007233 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007234 // Note that this is not the case for explicit specializations of
7235 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007236 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7237 // extension for compatibility with old SWIG code which likes to
7238 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007239 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7240 << D.getCXXScopeSpec().getRange();
7241 }
7242 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007243
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007244 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007245 checkAttributesAfterMerging(*this, *NewFD);
7246
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007247 AddKnownFunctionAttributes(NewFD);
7248
Douglas Gregor72609052010-08-06 13:50:58 +00007249 if (NewFD->hasAttr<OverloadableAttr>() &&
7250 !NewFD->getType()->getAs<FunctionProtoType>()) {
7251 Diag(NewFD->getLocation(),
7252 diag::err_attribute_overloadable_no_prototype)
7253 << NewFD;
7254
7255 // Turn this into a variadic function with no parameters.
7256 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007257 FunctionProtoType::ExtProtoInfo EPI(
7258 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007259 EPI.Variadic = true;
7260 EPI.ExtInfo = FT->getExtInfo();
7261
Alp Toker314cc812014-01-25 16:55:45 +00007262 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007263 NewFD->setType(R);
7264 }
7265
Eli Friedman570024a2010-08-05 06:57:20 +00007266 // If there's a #pragma GCC visibility in scope, and this isn't a class
7267 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007268 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007269 AddPushedVisibilityAttribute(NewFD);
7270
John McCall32f5fe12011-09-30 05:12:12 +00007271 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7272 // marking the function.
7273 AddCFAuditedAttribute(NewFD);
7274
Richard Smithac974a32013-06-30 09:48:50 +00007275 // If this is the first declaration of an extern C variable, update
7276 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007277 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007278 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007279 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007280
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007281 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007282 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007283
David Blaikiebbafb8a2012-03-11 07:00:24 +00007284 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007285 if (FunctionTemplate) {
7286 if (NewFD->isInvalidDecl())
7287 FunctionTemplate->setInvalidDecl();
7288 return FunctionTemplate;
7289 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007290 }
Mike Stump11289f42009-09-09 15:08:12 +00007291
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007292 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007293 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7294 if ((getLangOpts().OpenCLVersion >= 120)
7295 && (SC == SC_Static)) {
7296 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7297 D.setInvalidType();
7298 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007299
7300 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
Alp Toker314cc812014-01-25 16:55:45 +00007301 if (!NewFD->getReturnType()->isVoidType()) {
Tanya Lattner0f864332013-01-30 19:48:52 +00007302 Diag(D.getIdentifierLoc(),
7303 diag::err_expected_kernel_void_return_type);
7304 D.setInvalidType();
7305 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007306
7307 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00007308 for (auto Param : NewFD->params())
Matt Arsenaultefb38192013-07-23 01:23:36 +00007309 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007310 }
7311
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007312 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007313
David Blaikiebbafb8a2012-03-11 07:00:24 +00007314 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007315 if (IdentifierInfo *II = NewFD->getIdentifier())
7316 if (!NewFD->isInvalidDecl() &&
7317 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7318 if (II->isStr("cudaConfigureCall")) {
Alp Toker314cc812014-01-25 16:55:45 +00007319 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007320 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7321
7322 Context.setcudaConfigureCallDecl(NewFD);
7323 }
7324 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007325
7326 // Here we have an function template explicit specialization at class scope.
7327 // The actually specialization will be postponed to template instatiation
7328 // time via the ClassScopeFunctionSpecializationDecl node.
7329 if (isDependentClassScopeExplicitSpecialization) {
7330 ClassScopeFunctionSpecializationDecl *NewSpec =
7331 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007332 Context, CurContext, SourceLocation(),
7333 cast<CXXMethodDecl>(NewFD),
7334 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007335 CurContext->addDecl(NewSpec);
7336 AddToScope = false;
7337 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007338
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007339 return NewFD;
7340}
7341
7342/// \brief Perform semantic checking of a new function declaration.
7343///
7344/// Performs semantic analysis of the new function declaration
7345/// NewFD. This routine performs all semantic checking that does not
7346/// require the actual declarator involved in the declaration, and is
7347/// used both for the declaration of functions as they are parsed
7348/// (called via ActOnDeclarator) and for the declaration of functions
7349/// that have been instantiated via C++ template instantiation (called
7350/// via InstantiateDecl).
7351///
James Dennettffad8b72012-06-22 08:10:18 +00007352/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007353/// an explicit specialization of the previous declaration.
7354///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007355/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007356///
James Dennettffad8b72012-06-22 08:10:18 +00007357/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007358bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007359 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007360 bool IsExplicitSpecialization) {
Alp Toker314cc812014-01-25 16:55:45 +00007361 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7362 "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007363
Richard Smith1c34fb72013-08-13 18:18:50 +00007364 // Determine whether the type of this function should be merged with
7365 // a previous visible declaration. This never happens for functions in C++,
7366 // and always happens in C if the previous declaration was visible.
7367 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7368 !Previous.isShadowed();
7369
Douglas Gregor3552dab2013-01-09 00:47:56 +00007370 // Filter out any non-conflicting previous declarations.
7371 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7372
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007373 bool Redeclaration = false;
Richard Smith574f4f62013-01-14 05:37:29 +00007374 NamedDecl *OldDecl = 0;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007375
Douglas Gregore62c0a42009-02-24 01:23:02 +00007376 // Merge or overload the declaration with an existing declaration of
7377 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007378 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007379 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007380 // a declaration that requires merging. If it's an overload,
7381 // there's no more work to do here; we'll just add the new
7382 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007383 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007384 NamedDecl *Candidate = Previous.getFoundDecl();
7385 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7386 Redeclaration = true;
7387 OldDecl = Candidate;
7388 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007389 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007390 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7391 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007392 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007393 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007394 break;
7395
7396 case Ovl_NonFunction:
7397 Redeclaration = true;
7398 break;
7399
7400 case Ovl_Overload:
7401 Redeclaration = false;
7402 break;
John McCall1f82f242009-11-18 22:49:29 +00007403 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007404
David Blaikiebbafb8a2012-03-11 07:00:24 +00007405 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007406 // If a function name is overloadable in C, then every function
7407 // with that name must be marked "overloadable".
7408 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7409 << Redeclaration << NewFD;
7410 NamedDecl *OverloadedDecl = 0;
7411 if (Redeclaration)
7412 OverloadedDecl = OldDecl;
7413 else if (!Previous.empty())
7414 OverloadedDecl = Previous.getRepresentativeDecl();
7415 if (OverloadedDecl)
7416 Diag(OverloadedDecl->getLocation(),
7417 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007418 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007419 }
John McCall1f82f242009-11-18 22:49:29 +00007420 }
Richard Smith574f4f62013-01-14 05:37:29 +00007421 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007422
Richard Smithac974a32013-06-30 09:48:50 +00007423 // Check for a previous extern "C" declaration with this name.
7424 if (!Redeclaration &&
7425 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7426 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7427 if (!Previous.empty()) {
7428 // This is an extern "C" declaration with the same name as a previous
7429 // declaration, and thus redeclares that entity...
7430 Redeclaration = true;
7431 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007432 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007433
7434 // ... except in the presence of __attribute__((overloadable)).
7435 if (OldDecl->hasAttr<OverloadableAttr>()) {
7436 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7437 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7438 << Redeclaration << NewFD;
7439 Diag(Previous.getFoundDecl()->getLocation(),
7440 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007441 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007442 }
7443 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7444 Redeclaration = false;
7445 OldDecl = 0;
7446 }
7447 }
7448 }
7449 }
7450
Richard Smith574f4f62013-01-14 05:37:29 +00007451 // C++11 [dcl.constexpr]p8:
7452 // A constexpr specifier for a non-static member function that is not
7453 // a constructor declares that member function to be const.
7454 //
7455 // This needs to be delayed until we know whether this is an out-of-line
7456 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007457 //
7458 // This rule is not present in C++1y, so we produce a backwards
7459 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007460 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007461 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7462 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007463 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
Alp Tokera2794f92014-01-22 07:29:52 +00007464 CXXMethodDecl *OldMD = 0;
7465 if (OldDecl)
7466 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
Richard Smith574f4f62013-01-14 05:37:29 +00007467 if (!OldMD || !OldMD->isStatic()) {
7468 const FunctionProtoType *FPT =
7469 MD->getType()->castAs<FunctionProtoType>();
7470 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7471 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007472 MD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007473 FPT->getParamTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007474
7475 // Warn that we did this, if we're not performing template instantiation.
7476 // In that case, we'll have warned already when the template was defined.
7477 if (ActiveTemplateInstantiations.empty()) {
7478 SourceLocation AddConstLoc;
7479 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7480 .IgnoreParens().getAs<FunctionTypeLoc>())
7481 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7482
7483 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7484 << FixItHint::CreateInsertion(AddConstLoc, " const");
7485 }
Richard Smith574f4f62013-01-14 05:37:29 +00007486 }
7487 }
7488
7489 if (Redeclaration) {
7490 // NewFD and OldDecl represent declarations that need to be
7491 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007492 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007493 NewFD->setInvalidDecl();
7494 return Redeclaration;
7495 }
7496
7497 Previous.clear();
7498 Previous.addDecl(OldDecl);
7499
7500 if (FunctionTemplateDecl *OldTemplateDecl
7501 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7502 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7503 FunctionTemplateDecl *NewTemplateDecl
7504 = NewFD->getDescribedFunctionTemplate();
7505 assert(NewTemplateDecl && "Template/non-template mismatch");
7506 if (CXXMethodDecl *Method
7507 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7508 Method->setAccess(OldTemplateDecl->getAccess());
7509 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007510 }
Richard Smith574f4f62013-01-14 05:37:29 +00007511
7512 // If this is an explicit specialization of a member that is a function
7513 // template, mark it as a member specialization.
7514 if (IsExplicitSpecialization &&
7515 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7516 NewTemplateDecl->setMemberSpecialization();
7517 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007518 }
Richard Smith574f4f62013-01-14 05:37:29 +00007519
7520 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007521 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007522 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007523
7524 if (isa<CXXMethodDecl>(NewFD)) {
7525 // A valid redeclaration of a C++ method must be out-of-line,
7526 // but (unfortunately) it's not necessarily a definition
7527 // because of templates, which means that the previous
7528 // declaration is not necessarily from the class definition.
7529
7530 // For just setting the access, that doesn't matter.
7531 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7532 NewFD->setAccess(oldMethod->getAccess());
7533
7534 // Update the key-function state if necessary for this ABI.
7535 if (NewFD->isInlined() &&
7536 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7537 // setNonKeyFunction needs to work with the original
7538 // declaration from the class definition, and isVirtual() is
7539 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007540 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007541 if (oldMethod->isVirtual()) {
7542 Context.setNonKeyFunction(oldMethod);
7543 }
7544 }
7545 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007546 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007547 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007548
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007549 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007550 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007551 // C++-specific checks.
7552 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7553 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007554 } else if (CXXDestructorDecl *Destructor =
7555 dyn_cast<CXXDestructorDecl>(NewFD)) {
7556 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007557 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007558
Douglas Gregor7454c562010-07-02 20:37:36 +00007559 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007560 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007561 if (!ClassType->isDependentType()) {
7562 DeclarationName Name
7563 = Context.DeclarationNames.getCXXDestructorName(
7564 Context.getCanonicalType(ClassType));
7565 if (NewFD->getDeclName() != Name) {
7566 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007567 NewFD->setInvalidDecl();
7568 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007569 }
7570 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007571 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007572 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007573 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007574 }
7575
7576 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7578 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007579 !Method->getDescribedFunctionTemplate() &&
7580 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007581 if (AddOverriddenMethods(Method->getParent(), Method)) {
7582 // If the function was marked as "static", we have a problem.
7583 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007584 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007585 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007586 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007587 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007588
7589 if (Method->isStatic())
7590 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007591 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007592
7593 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7594 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007595 CheckOverloadedOperatorDeclaration(NewFD)) {
7596 NewFD->setInvalidDecl();
7597 return Redeclaration;
7598 }
Alexis Huntc88db062010-01-13 09:01:02 +00007599
7600 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7601 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007602 CheckLiteralOperatorDeclaration(NewFD)) {
7603 NewFD->setInvalidDecl();
7604 return Redeclaration;
7605 }
Alexis Huntc88db062010-01-13 09:01:02 +00007606
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007607 // In C++, check default arguments now that we have merged decls. Unless
7608 // the lexical context is the class, because in this case this is done
7609 // during delayed parsing anyway.
7610 if (!CurContext->isRecord())
7611 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007612
Douglas Gregor9246b682010-12-21 19:47:46 +00007613 // If this function declares a builtin function, check the type of this
7614 // declaration against the expected type for the builtin.
7615 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7616 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007617 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007618 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7619 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7620 // The type of this function differs from the type of the builtin,
7621 // so forget about the builtin entirely.
7622 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7623 }
7624 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007625
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007626 // If this function is declared as being extern "C", then check to see if
7627 // the function returns a UDT (class, struct, or union type) that is not C
7628 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007629 // But, issue any diagnostic on the first declaration only.
7630 if (NewFD->isExternC() && Previous.empty()) {
Alp Toker314cc812014-01-25 16:55:45 +00007631 QualType R = NewFD->getReturnType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007632 if (R->isIncompleteType() && !R->isVoidType())
7633 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7634 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007635 else if (!R.isPODType(Context) && !R->isVoidType() &&
7636 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007637 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007638 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007639 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007640 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007641}
7642
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007643static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7644 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7645 if (!TSI)
7646 return SourceRange();
7647
7648 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007649 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007650 if (!FunctionTL)
7651 return SourceRange();
7652
Alp Toker42a16a62014-01-25 23:51:36 +00007653 TypeLoc ResultTL = FunctionTL.getReturnLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007654 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007655 return ResultTL.getSourceRange();
7656
7657 return SourceRange();
7658}
7659
David Blaikied937bf12011-09-08 06:33:04 +00007660void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smithb63b6ee2014-01-22 01:43:19 +00007661 // C++11 [basic.start.main]p3:
7662 // A program that [...] declares main to be inline, static or
7663 // constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007664 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7665 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007666 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007667 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007668 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007669 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007670 ? diag::err_static_main : diag::warn_static_main)
7671 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7672 if (FD->isInlineSpecified())
7673 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7674 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007675 if (DS.isNoreturnSpecified()) {
7676 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7677 SourceRange NoreturnRange(NoreturnLoc,
7678 PP.getLocForEndOfToken(NoreturnLoc));
7679 Diag(NoreturnLoc, diag::ext_noreturn_main);
7680 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7681 << FixItHint::CreateRemoval(NoreturnRange);
7682 }
Richard Smith3f333f22012-02-04 06:10:17 +00007683 if (FD->isConstexpr()) {
7684 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7685 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7686 FD->setConstexpr(false);
7687 }
John McCall02dee0a2009-07-25 04:36:53 +00007688
Joey Goulya7310a82013-11-05 12:30:39 +00007689 if (getLangOpts().OpenCL) {
7690 Diag(FD->getLocation(), diag::err_opencl_no_main)
7691 << FD->hasAttr<OpenCLKernelAttr>();
7692 FD->setInvalidDecl();
7693 return;
7694 }
7695
John McCall02dee0a2009-07-25 04:36:53 +00007696 QualType T = FD->getType();
7697 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007698 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007699
John McCall5ed3caf2012-02-14 19:50:52 +00007700 // All the standards say that main() should should return 'int'.
Alp Toker314cc812014-01-25 16:55:45 +00007701 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
John McCall5ed3caf2012-02-14 19:50:52 +00007702 // In C and C++, main magically returns 0 if you fall off the end;
7703 // set the flag which tells us that.
7704 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7705 FD->setHasImplicitReturnZero(true);
7706
7707 // In C with GNU extensions we allow main() to have non-integer return
7708 // type, but we should warn about the extension, and we disable the
7709 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007710 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007711 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7712
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007713 SourceRange ResultRange = getResultSourceRange(FD);
7714 if (ResultRange.isValid())
7715 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7716 << FixItHint::CreateReplacement(ResultRange, "int");
7717
John McCall5ed3caf2012-02-14 19:50:52 +00007718 // Otherwise, this is just a flat-out error.
7719 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007720 SourceRange ResultRange = getResultSourceRange(FD);
7721 if (ResultRange.isValid())
7722 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7723 << FixItHint::CreateReplacement(ResultRange, "int");
7724 else
7725 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7726
John McCall02dee0a2009-07-25 04:36:53 +00007727 FD->setInvalidDecl(true);
7728 }
7729
7730 // Treat protoless main() as nullary.
7731 if (isa<FunctionNoProtoType>(FT)) return;
7732
7733 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00007734 unsigned nparams = FTP->getNumParams();
John McCall02dee0a2009-07-25 04:36:53 +00007735 assert(FD->getNumParams() == nparams);
7736
John McCall0e21fcc2009-12-24 09:58:38 +00007737 bool HasExtraParameters = (nparams > 3);
7738
7739 // Darwin passes an undocumented fourth argument of type char**. If
7740 // other platforms start sprouting these, the logic below will start
7741 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007742 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007743 HasExtraParameters = false;
7744
7745 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007746 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7747 FD->setInvalidDecl(true);
7748 nparams = 3;
7749 }
7750
7751 // FIXME: a lot of the following diagnostics would be improved
7752 // if we had some location information about types.
7753
7754 QualType CharPP =
7755 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007756 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007757
7758 for (unsigned i = 0; i < nparams; ++i) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007759 QualType AT = FTP->getParamType(i);
John McCall02dee0a2009-07-25 04:36:53 +00007760
7761 bool mismatch = true;
7762
7763 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7764 mismatch = false;
7765 else if (Expected[i] == CharPP) {
7766 // As an extension, the following forms are okay:
7767 // char const **
7768 // char const * const *
7769 // char * const *
7770
John McCall8ccfcb52009-09-24 19:53:00 +00007771 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007772 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007773 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7774 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007775 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7776 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007777 qs.removeConst();
7778 mismatch = !qs.empty();
7779 }
7780 }
7781
7782 if (mismatch) {
7783 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7784 // TODO: suggest replacing given type with expected type
7785 FD->setInvalidDecl(true);
7786 }
7787 }
7788
7789 if (nparams == 1 && !FD->isInvalidDecl()) {
7790 Diag(FD->getLocation(), diag::warn_main_one_arg);
7791 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007792
7793 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007794 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007795 FD->setInvalidDecl();
7796 }
7797}
7798
7799void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7800 QualType T = FD->getType();
7801 assert(T->isFunctionType() && "function decl is not of function type");
7802 const FunctionType *FT = T->castAs<FunctionType>();
7803
7804 // Set an implicit return of 'zero' if the function can return some integral,
7805 // enumeration, pointer or nullptr type.
Alp Toker314cc812014-01-25 16:55:45 +00007806 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7807 FT->getReturnType()->isAnyPointerType() ||
7808 FT->getReturnType()->isNullPtrType())
David Majnemerc729b0b2013-09-16 22:44:20 +00007809 // DllMain is exempt because a return value of zero means it failed.
7810 if (FD->getName() != "DllMain")
7811 FD->setHasImplicitReturnZero(true);
7812
7813 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007814 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007815 FD->setInvalidDecl();
7816 }
John McCalld9baf6a2009-07-24 03:03:21 +00007817}
7818
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007819bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007820 // FIXME: Need strict checking. In C89, we need to check for
7821 // any assignment, increment, decrement, function-calls, or
7822 // commas outside of a sizeof. In C99, it's the same list,
7823 // except that the aforementioned are allowed in unevaluated
7824 // expressions. Everything else falls under the
7825 // "may accept other forms of constant expressions" exception.
7826 // (We never end up here for C++, so the constant expression
7827 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007828 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007829 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007830 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7831 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007832 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007833}
7834
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007835namespace {
7836 // Visits an initialization expression to see if OrigDecl is evaluated in
7837 // its own initialization and throws a warning if it does.
7838 class SelfReferenceChecker
7839 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7840 Sema &S;
7841 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007842 bool isRecordType;
7843 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007844 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007845
7846 public:
7847 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7848
7849 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007850 S(S), OrigDecl(OrigDecl) {
7851 isPODType = false;
7852 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007853 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007854 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7855 isPODType = VD->getType().isPODType(S.Context);
7856 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007857 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007858 }
7859 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007860
Richard Trieu64c51ab2012-05-09 00:21:34 +00007861 // For most expressions, the cast is directly above the DeclRefExpr.
7862 // For conditional operators, the cast can be outside the conditional
7863 // operator if both expressions are DeclRefExpr's.
7864 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007865 if (isReferenceType)
7866 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007867 E = E->IgnoreParenImpCasts();
7868 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7869 HandleDeclRefExpr(DRE);
7870 return;
7871 }
7872
7873 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7874 HandleValue(CO->getTrueExpr());
7875 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007876 return;
7877 }
7878
7879 if (isa<MemberExpr>(E)) {
7880 Expr *Base = E->IgnoreParenImpCasts();
7881 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7882 // Check for static member variables and don't warn on them.
7883 if (!isa<FieldDecl>(ME->getMemberDecl()))
7884 return;
7885 Base = ME->getBase()->IgnoreParenImpCasts();
7886 }
7887 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7888 HandleDeclRefExpr(DRE);
7889 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007890 }
7891 }
7892
Richard Trieu32673472012-10-01 17:39:51 +00007893 // Reference types are handled here since all uses of references are
7894 // bad, not just r-value uses.
7895 void VisitDeclRefExpr(DeclRefExpr *E) {
7896 if (isReferenceType)
7897 HandleDeclRefExpr(E);
7898 }
7899
Richard Trieu64c51ab2012-05-09 00:21:34 +00007900 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00007901 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00007902 (isRecordType && E->getCastKind() == CK_NoOp))
7903 HandleValue(E->getSubExpr());
7904
7905 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007906 }
7907
Richard Trieua04ad1a2011-09-01 21:44:13 +00007908 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00007909 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00007910 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007911
Richard Trieu742c6ed2012-10-03 00:41:36 +00007912 // Warn when a non-static method call is followed by non-static member
7913 // field accesses, which is followed by a DeclRefExpr.
7914 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7915 bool Warn = (MD && !MD->isStatic());
7916 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7917 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7918 if (!isa<FieldDecl>(ME->getMemberDecl()))
7919 Warn = false;
7920 Base = ME->getBase()->IgnoreParenImpCasts();
7921 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007922
Richard Trieu742c6ed2012-10-03 00:41:36 +00007923 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7924 if (Warn)
7925 HandleDeclRefExpr(DRE);
7926 return;
7927 }
7928
7929 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7930 // Visit that expression.
7931 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007932 }
7933
Richard Trieu8fbd91d2013-03-26 03:41:40 +00007934 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7935 if (E->getNumArgs() > 0)
7936 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7937 HandleDeclRefExpr(DRE);
7938
7939 Inherited::VisitCXXOperatorCallExpr(E);
7940 }
7941
Richard Trieua04ad1a2011-09-01 21:44:13 +00007942 void VisitUnaryOperator(UnaryOperator *E) {
7943 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00007944 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7945 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7946 if (!isPODType)
7947 HandleValue(E->getSubExpr());
7948 return;
7949 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007950 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00007951 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00007952
7953 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7954
Richard Trieua04ad1a2011-09-01 21:44:13 +00007955 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00007956 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007957 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00007958 unsigned diag;
7959 if (isReferenceType) {
7960 diag = diag::warn_uninit_self_reference_in_reference_init;
7961 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7962 diag = diag::warn_static_self_reference_in_init;
7963 } else {
7964 diag = diag::warn_uninit_self_reference_in_init;
7965 }
7966
Richard Trieua04ad1a2011-09-01 21:44:13 +00007967 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00007968 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00007969 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007970 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00007971 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007972 }
7973 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007974
Richard Trieu32673472012-10-01 17:39:51 +00007975 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7976 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7977 bool DirectInit) {
7978 // Parameters arguments are occassionially constructed with itself,
7979 // for instance, in recursive functions. Skip them.
7980 if (isa<ParmVarDecl>(OrigDecl))
7981 return;
7982
7983 E = E->IgnoreParens();
7984
7985 // Skip checking T a = a where T is not a record or reference type.
7986 // Doing so is a way to silence uninitialized warnings.
7987 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7988 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7989 if (ICE->getCastKind() == CK_LValueToRValue)
7990 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7991 if (DRE->getDecl() == OrigDecl)
7992 return;
7993
7994 SelfReferenceChecker(S, OrigDecl).Visit(E);
7995 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007996}
7997
Douglas Gregor5fb53972009-01-14 15:45:31 +00007998/// AddInitializerToDecl - Adds the initializer Init to the
7999/// declaration dcl. If DirectInit is true, this is C++ direct
8000/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008001void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8002 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008003 // If there is no declaration, there was an error parsing it. Just ignore
8004 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008005 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008006 return;
Mike Stump11289f42009-09-09 15:08:12 +00008007
Douglas Gregor0c880302009-03-11 23:00:04 +00008008 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8009 // With declarators parsed the way they are, the parser cannot
8010 // distinguish between a normal initializer and a pure-specifier.
8011 // Thus this grotesque test.
8012 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008013 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008014 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8015 CheckPureMethod(Method, Init->getSourceRange());
8016 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008017 Diag(Method->getLocation(), diag::err_member_function_initialization)
8018 << Method->getDeclName() << Init->getSourceRange();
8019 Method->setInvalidDecl();
8020 }
8021 return;
8022 }
8023
Steve Naroff437b4d82007-09-12 20:13:48 +00008024 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8025 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008026 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8027 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008028 RealDecl->setInvalidDecl();
8029 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008030 }
Sebastian Redla9351792012-02-11 23:51:47 +00008031 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8032
Richard Smith0cc85782011-12-15 19:20:59 +00008033 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008034 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008035 Expr *DeduceInit = Init;
8036 // Initializer could be a C++ direct-initializer. Deduction only works if it
8037 // contains exactly one expression.
8038 if (CXXDirectInit) {
8039 if (CXXDirectInit->getNumExprs() == 0) {
8040 // It isn't possible to write this directly, but it is possible to
8041 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008042 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008043 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8044 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008045 << VDecl->getDeclName() << VDecl->getType()
8046 << VDecl->getSourceRange();
8047 RealDecl->setInvalidDecl();
8048 return;
8049 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008050 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008051 VDecl->isInitCapture()
8052 ? diag::err_init_capture_multiple_expressions
8053 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008054 << VDecl->getDeclName() << VDecl->getType()
8055 << VDecl->getSourceRange();
8056 RealDecl->setInvalidDecl();
8057 return;
8058 } else {
8059 DeduceInit = CXXDirectInit->getExpr(0);
Richard Smith66204ec2014-03-12 17:42:45 +00008060 if (isa<InitListExpr>(DeduceInit))
8061 Diag(CXXDirectInit->getLocStart(),
8062 diag::err_auto_var_init_paren_braces)
8063 << VDecl->getDeclName() << VDecl->getType()
8064 << VDecl->getSourceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00008065 }
8066 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008067
8068 // Expressions default to 'id' when we're in a debugger.
8069 bool DefaultedToAuto = false;
8070 if (getLangOpts().DebuggerCastResultToId &&
8071 Init->getType() == Context.UnknownAnyTy) {
8072 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8073 if (Result.isInvalid()) {
8074 VDecl->setInvalidDecl();
8075 return;
8076 }
8077 Init = Result.take();
8078 DefaultedToAuto = true;
8079 }
Richard Smith061f1e22013-04-30 21:23:01 +00008080
8081 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008082 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008083 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008084 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008085 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008086 RealDecl->setInvalidDecl();
8087 return;
8088 }
Richard Smith061f1e22013-04-30 21:23:01 +00008089 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008090 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008091
John McCall31168b02011-06-15 23:02:42 +00008092 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008093 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008094 VDecl->setInvalidDecl();
8095
Jordan Rosed8d56692012-06-08 22:46:07 +00008096 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8097 // 'id' instead of a specific object type prevents most of our usual checks.
8098 // We only want to warn outside of template instantiations, though:
8099 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008100 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008101 DeducedType->isObjCIdType()) {
8102 SourceLocation Loc =
8103 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008104 Diag(Loc, diag::warn_auto_var_is_id)
8105 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8106 }
8107
Richard Smith30482bc2011-02-20 03:19:35 +00008108 // If this is a redeclaration, check that the type we just deduced matches
8109 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008110 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8111 // We never need to merge the type, because we cannot form an incomplete
8112 // array of auto, nor deduce such a type.
8113 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8114 }
Richard Smith27d807c2013-04-30 13:56:41 +00008115
8116 // Check the deduced type is valid for a variable declaration.
8117 CheckVariableDeclarationType(VDecl);
8118 if (VDecl->isInvalidDecl())
8119 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008120 }
Richard Smith0cc85782011-12-15 19:20:59 +00008121
Nico Rieck8e9791f2014-02-26 21:27:13 +00008122 // dllimport cannot be used on variable definitions.
8123 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8124 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8125 VDecl->setInvalidDecl();
8126 return;
8127 }
8128
Richard Smith0cc85782011-12-15 19:20:59 +00008129 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8130 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8131 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8132 VDecl->setInvalidDecl();
8133 return;
8134 }
8135
Sebastian Redla9351792012-02-11 23:51:47 +00008136 if (!VDecl->getType()->isDependentType()) {
8137 // A definition must end up with a complete type, which means it must be
8138 // complete with the restriction that an array type might be completed by
8139 // the initializer; note that later code assumes this restriction.
8140 QualType BaseDeclType = VDecl->getType();
8141 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8142 BaseDeclType = Array->getElementType();
8143 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8144 diag::err_typecheck_decl_incomplete_type)) {
8145 RealDecl->setInvalidDecl();
8146 return;
8147 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008148
Sebastian Redla9351792012-02-11 23:51:47 +00008149 // The variable can not have an abstract class type.
8150 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8151 diag::err_abstract_type_in_decl,
8152 AbstractVariableType))
8153 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008154 }
8155
Sebastian Redl5ca79842010-02-01 20:16:42 +00008156 const VarDecl *Def;
8157 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008158 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008159 << VDecl->getDeclName();
8160 Diag(Def->getLocation(), diag::note_previous_definition);
8161 VDecl->setInvalidDecl();
8162 return;
8163 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008164
Douglas Gregorf0f83692010-08-24 05:27:49 +00008165 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008166 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008167 // C++ [class.static.data]p4
8168 // If a static data member is of const integral or const
8169 // enumeration type, its declaration in the class definition can
8170 // specify a constant-initializer which shall be an integral
8171 // constant expression (5.19). In that case, the member can appear
8172 // in integral constant expressions. The member shall still be
8173 // defined in a namespace scope if it is used in the program and the
8174 // namespace scope definition shall not contain an initializer.
8175 //
8176 // We already performed a redefinition check above, but for static
8177 // data members we also need to check whether there was an in-class
8178 // declaration with an initializer.
8179 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008180 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8181 << VDecl->getDeclName();
8182 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008183 return;
8184 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008185
Douglas Gregor71f39c92010-12-16 01:31:22 +00008186 if (VDecl->hasLocalStorage())
8187 getCurFunction()->setHasBranchProtectedScope();
8188
8189 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8190 VDecl->setInvalidDecl();
8191 return;
8192 }
8193 }
John McCalld4e1b762010-08-01 01:24:59 +00008194
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008195 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8196 // a kernel function cannot be initialized."
8197 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8198 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8199 VDecl->setInvalidDecl();
8200 return;
8201 }
8202
Steve Naroff61091402007-09-12 14:07:44 +00008203 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008204 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008205 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008206
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008207 // Expressions default to 'id' when we're in a debugger
8208 // and we are assigning it to a variable of Objective-C pointer type.
8209 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8210 Init->getType() == Context.UnknownAnyTy) {
8211 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8212 if (Result.isInvalid()) {
8213 VDecl->setInvalidDecl();
8214 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008215 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008216 Init = Result.take();
8217 }
Richard Smith0cc85782011-12-15 19:20:59 +00008218
8219 // Perform the initialization.
8220 if (!VDecl->isInvalidDecl()) {
8221 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8222 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008223 = DirectInit ?
8224 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8225 Init->getLocStart(),
8226 Init->getLocEnd())
8227 : InitializationKind::CreateDirectList(
8228 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008229 : InitializationKind::CreateCopy(VDecl->getLocation(),
8230 Init->getLocStart());
8231
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008232 MultiExprArg Args = Init;
8233 if (CXXDirectInit)
8234 Args = MultiExprArg(CXXDirectInit->getExprs(),
8235 CXXDirectInit->getNumExprs());
8236
8237 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8238 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008239 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008240 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008241 return;
Steve Naroff61091402007-09-12 14:07:44 +00008242 }
Richard Smith0cc85782011-12-15 19:20:59 +00008243
8244 Init = Result.takeAs<Expr>();
8245 }
8246
Richard Trieu32673472012-10-01 17:39:51 +00008247 // Check for self-references within variable initializers.
8248 // Variables declared within a function/method body (except for references)
8249 // are handled by a dataflow analysis.
8250 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8251 VDecl->getType()->isReferenceType()) {
8252 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8253 }
8254
Richard Smith0cc85782011-12-15 19:20:59 +00008255 // If the type changed, it means we had an incomplete type that was
8256 // completed by the initializer. For example:
8257 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008258 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008259 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008260 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008261
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008262 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008263 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8264
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008265 if (VDecl->hasAttr<BlocksAttr>())
8266 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008267
8268 // It is safe to assign a weak reference into a strong variable.
8269 // Although this code can still have problems:
8270 // id x = self.weakProp;
8271 // id y = self.weakProp;
8272 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8273 // paths through the function. This should be revisited if
8274 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008275 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008276 DiagnosticsEngine::Level Level =
8277 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8278 Init->getLocStart());
8279 if (Level != DiagnosticsEngine::Ignored)
8280 getCurFunction()->markSafeWeakUse(Init);
8281 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008282 }
8283
Richard Smith945f8d32013-01-14 22:39:08 +00008284 // The initialization is usually a full-expression.
8285 //
8286 // FIXME: If this is a braced initialization of an aggregate, it is not
8287 // an expression, and each individual field initializer is a separate
8288 // full-expression. For instance, in:
8289 //
8290 // struct Temp { ~Temp(); };
8291 // struct S { S(Temp); };
8292 // struct T { S a, b; } t = { Temp(), Temp() }
8293 //
8294 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008295 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8296 false,
8297 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008298 if (Result.isInvalid()) {
8299 VDecl->setInvalidDecl();
8300 return;
8301 }
8302 Init = Result.take();
8303
Richard Smith0cc85782011-12-15 19:20:59 +00008304 // Attach the initializer to the decl.
8305 VDecl->setInit(Init);
8306
8307 if (VDecl->isLocalVarDecl()) {
8308 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8309 // static storage duration shall be constant expressions or string literals.
8310 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008311 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8312 if (VDecl->getStorageClass() == SC_Static)
8313 CheckForConstantInitializer(Init, DclT);
8314 // C89 is stricter than C99 for non-static aggregate types.
8315 // C89 6.5.7p3: All the expressions [...] in an initializer list
8316 // for an object that has aggregate or union type shall be
8317 // constant expressions.
8318 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008319 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008320 !Init->isConstantInitializer(Context, false))
8321 Diag(Init->getExprLoc(),
8322 diag::ext_aggregate_init_not_constant)
8323 << Init->getSourceRange();
8324 }
Mike Stump11289f42009-09-09 15:08:12 +00008325 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008326 VDecl->getLexicalDeclContext()->isRecord()) {
8327 // This is an in-class initialization for a static data member, e.g.,
8328 //
8329 // struct S {
8330 // static const int value = 17;
8331 // };
8332
Douglas Gregor0c880302009-03-11 23:00:04 +00008333 // C++ [class.mem]p4:
8334 // A member-declarator can contain a constant-initializer only
8335 // if it declares a static member (9.4) of const integral or
8336 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008337 //
Richard Smith0cc85782011-12-15 19:20:59 +00008338 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008339 // If a non-volatile const static data member is of integral or
8340 // enumeration type, its declaration in the class definition can
8341 // specify a brace-or-equal-initializer in which every initalizer-clause
8342 // that is an assignment-expression is a constant expression. A static
8343 // data member of literal type can be declared in the class definition
8344 // with the constexpr specifier; if so, its declaration shall specify a
8345 // brace-or-equal-initializer in which every initializer-clause that is
8346 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008347
8348 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008349 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008350
Richard Smith2316cd82011-09-29 19:11:37 +00008351 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008352 // type. We separately check that every constexpr variable is of literal
8353 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008354 } else if (VDecl->isConstexpr()) {
8355
John McCalldb768922010-09-10 23:21:22 +00008356 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008357 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008358 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8359 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008360 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008361
8362 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008363 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008364 // Check whether the expression is a constant expression.
8365 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008366 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008367 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008368 // in-class initializer cannot be volatile.
8369 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8370 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008371 ; // Nothing to check.
8372 else if (Init->isIntegerConstantExpr(Context, &Loc))
8373 ; // Ok, it's an ICE!
8374 else if (Init->isEvaluatable(Context)) {
8375 // If we can constant fold the initializer through heroics, accept it,
8376 // but report this as a use of an extension for -pedantic.
8377 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8378 << Init->getSourceRange();
8379 } else {
8380 // Otherwise, this is some crazy unknown case. Report the issue at the
8381 // location provided by the isIntegerConstantExpr failed check.
8382 Diag(Loc, diag::err_in_class_initializer_non_constant)
8383 << Init->getSourceRange();
8384 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008385 }
8386
Richard Smith0cc85782011-12-15 19:20:59 +00008387 // We allow foldable floating-point constants as an extension.
8388 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008389 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8390 // it anyway and provide a fixit to add the 'constexpr'.
8391 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008392 Diag(VDecl->getLocation(),
8393 diag::ext_in_class_initializer_float_type_cxx11)
8394 << DclT << Init->getSourceRange();
8395 Diag(VDecl->getLocStart(),
8396 diag::note_in_class_initializer_float_type_cxx11)
8397 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008398 } else {
8399 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8400 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008401
Richard Smithcf656382013-01-25 04:22:16 +00008402 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8403 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8404 << Init->getSourceRange();
8405 VDecl->setInvalidDecl();
8406 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008407 }
Richard Smith256336d2011-09-29 23:18:34 +00008408
Richard Smith0cc85782011-12-15 19:20:59 +00008409 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008410 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008411 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008412 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008413 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8414 VDecl->setConstexpr(true);
8415
Richard Smith2316cd82011-09-29 19:11:37 +00008416 } else {
8417 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008418 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008419 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008420 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008421 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008422 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008423 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008424 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008425 VDecl->isExternC())) &&
8426 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008427 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008428
Richard Smith0cc85782011-12-15 19:20:59 +00008429 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008430 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008431 CheckForConstantInitializer(Init, DclT);
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008432 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8433 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8434 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smith774672e2013-04-15 08:07:34 +00008435 !Init->isConstantInitializer(
8436 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008437 // GNU C++98 edits for __thread, [basic.start.init]p4:
8438 // An object of thread storage duration shall not require dynamic
8439 // initialization.
8440 // FIXME: Need strict checking here.
8441 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8442 if (getLangOpts().CPlusPlus11)
8443 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8444 }
Steve Naroff61091402007-09-12 14:07:44 +00008445 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008446
Sebastian Redla9351792012-02-11 23:51:47 +00008447 // We will represent direct-initialization similarly to copy-initialization:
8448 // int x(1); -as-> int x = 1;
8449 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8450 //
8451 // Clients that want to distinguish between the two forms, can check for
8452 // direct initializer using VarDecl::getInitStyle().
8453 // A major benefit is that clients that don't particularly care about which
8454 // exactly form was it (like the CodeGen) can handle both cases without
8455 // special case code.
8456
8457 // C++ 8.5p11:
8458 // The form of initialization (using parentheses or '=') is generally
8459 // insignificant, but does matter when the entity being initialized has a
8460 // class type.
8461 if (CXXDirectInit) {
8462 assert(DirectInit && "Call-style initializer must be direct init.");
8463 VDecl->setInitStyle(VarDecl::CallInit);
8464 } else if (DirectInit) {
8465 // This must be list-initialization. No other way is direct-initialization.
8466 VDecl->setInitStyle(VarDecl::ListInit);
8467 }
8468
John McCall8b7fd8f12011-01-19 11:48:09 +00008469 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008470}
8471
John McCalleae5acb2010-03-31 02:13:20 +00008472/// ActOnInitializerError - Given that there was an error parsing an
8473/// initializer for the given declaration, try to return to some form
8474/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008475void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008476 // Our main concern here is re-establishing invariants like "a
8477 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008478 if (!D || D->isInvalidDecl()) return;
8479
8480 VarDecl *VD = dyn_cast<VarDecl>(D);
8481 if (!VD) return;
8482
Richard Smith30482bc2011-02-20 03:19:35 +00008483 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008484 if (ParsingInitForAutoVars.count(D)) {
8485 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008486 return;
8487 }
8488
John McCalleae5acb2010-03-31 02:13:20 +00008489 QualType Ty = VD->getType();
8490 if (Ty->isDependentType()) return;
8491
8492 // Require a complete type.
8493 if (RequireCompleteType(VD->getLocation(),
8494 Context.getBaseElementType(Ty),
8495 diag::err_typecheck_decl_incomplete_type)) {
8496 VD->setInvalidDecl();
8497 return;
8498 }
8499
8500 // Require an abstract type.
8501 if (RequireNonAbstractType(VD->getLocation(), Ty,
8502 diag::err_abstract_type_in_decl,
8503 AbstractVariableType)) {
8504 VD->setInvalidDecl();
8505 return;
8506 }
8507
8508 // Don't bother complaining about constructors or destructors,
8509 // though.
8510}
8511
John McCall48871652010-08-21 09:40:31 +00008512void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008513 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008514 // If there is no declaration, there was an error parsing it. Just ignore it.
8515 if (RealDecl == 0)
8516 return;
8517
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008518 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8519 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008520
Richard Smithf0215fe2011-12-25 21:17:58 +00008521 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008522 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008523 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8524 << Var->getDeclName() << Type;
8525 Var->setInvalidDecl();
8526 return;
8527 }
Mike Stump11289f42009-09-09 15:08:12 +00008528
Richard Smithf0215fe2011-12-25 21:17:58 +00008529 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008530 // the constexpr specifier; if so, its declaration shall specify
8531 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008532 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8533 // the definition of a variable [...] or the declaration of a static data
8534 // member.
8535 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8536 if (Var->isStaticDataMember())
8537 Diag(Var->getLocation(),
8538 diag::err_constexpr_static_mem_var_requires_init)
8539 << Var->getDeclName();
8540 else
8541 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008542 Var->setInvalidDecl();
8543 return;
8544 }
8545
Joey Gouly96b94e62014-01-03 14:16:55 +00008546 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8547 // be initialized.
8548 if (!Var->isInvalidDecl() &&
8549 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Pekka Jaaskelainenb3cdee02014-01-23 16:21:02 +00008550 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
Joey Gouly96b94e62014-01-03 14:16:55 +00008551 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8552 Var->setInvalidDecl();
8553 return;
8554 }
8555
Douglas Gregore6565622010-02-09 07:26:29 +00008556 switch (Var->isThisDeclarationADefinition()) {
8557 case VarDecl::Definition:
8558 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8559 break;
8560
8561 // We have an out-of-line definition of a static data member
8562 // that has an in-class initializer, so we type-check this like
8563 // a declaration.
8564 //
8565 // Fall through
8566
8567 case VarDecl::DeclarationOnly:
8568 // It's only a declaration.
8569
8570 // Block scope. C99 6.7p7: If an identifier for an object is
8571 // declared with no linkage (C99 6.2.2p6), the type for the
8572 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008573 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008574 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008575 RequireCompleteType(Var->getLocation(), Type,
8576 diag::err_typecheck_decl_incomplete_type))
8577 Var->setInvalidDecl();
8578
8579 // Make sure that the type is not abstract.
8580 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8581 RequireNonAbstractType(Var->getLocation(), Type,
8582 diag::err_abstract_type_in_decl,
8583 AbstractVariableType))
8584 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008585 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008586 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008587 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008588 Diag(Var->getLocation(), diag::note_private_extern);
8589 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008590
Douglas Gregore6565622010-02-09 07:26:29 +00008591 return;
8592
8593 case VarDecl::TentativeDefinition:
8594 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8595 // object that has file scope without an initializer, and without a
8596 // storage-class specifier or with the storage-class specifier "static",
8597 // constitutes a tentative definition. Note: A tentative definition with
8598 // external linkage is valid (C99 6.2.2p5).
8599 if (!Var->isInvalidDecl()) {
8600 if (const IncompleteArrayType *ArrayT
8601 = Context.getAsIncompleteArrayType(Type)) {
8602 if (RequireCompleteType(Var->getLocation(),
8603 ArrayT->getElementType(),
8604 diag::err_illegal_decl_array_incomplete_type))
8605 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008606 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008607 // C99 6.9.2p3: If the declaration of an identifier for an object is
8608 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8609 // declared type shall not be an incomplete type.
8610 // NOTE: code such as the following
8611 // static struct s;
8612 // struct s { int a; };
8613 // is accepted by gcc. Hence here we issue a warning instead of
8614 // an error and we do not invalidate the static declaration.
8615 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008616 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008617 RequireCompleteType(Var->getLocation(), Type,
8618 diag::ext_typecheck_decl_incomplete_type);
8619 }
8620 }
8621
8622 // Record the tentative definition; we're done.
8623 if (!Var->isInvalidDecl())
8624 TentativeDefinitions.push_back(Var);
8625 return;
8626 }
8627
8628 // Provide a specific diagnostic for uninitialized variable
8629 // definitions with incomplete array type.
8630 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008631 Diag(Var->getLocation(),
8632 diag::err_typecheck_incomplete_array_needs_initializer);
8633 Var->setInvalidDecl();
8634 return;
8635 }
8636
John McCalla755f0f2010-08-01 01:25:24 +00008637 // Provide a specific diagnostic for uninitialized variable
8638 // definitions with reference type.
8639 if (Type->isReferenceType()) {
8640 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8641 << Var->getDeclName()
8642 << SourceRange(Var->getLocation(), Var->getLocation());
8643 Var->setInvalidDecl();
8644 return;
8645 }
Douglas Gregore6565622010-02-09 07:26:29 +00008646
8647 // Do not attempt to type-check the default initializer for a
8648 // variable with dependent type.
8649 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008650 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008651
Douglas Gregore6565622010-02-09 07:26:29 +00008652 if (Var->isInvalidDecl())
8653 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008654
Douglas Gregore6565622010-02-09 07:26:29 +00008655 if (RequireCompleteType(Var->getLocation(),
8656 Context.getBaseElementType(Type),
8657 diag::err_typecheck_decl_incomplete_type)) {
8658 Var->setInvalidDecl();
8659 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008660 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008661
Douglas Gregore6565622010-02-09 07:26:29 +00008662 // The variable can not have an abstract class type.
8663 if (RequireNonAbstractType(Var->getLocation(), Type,
8664 diag::err_abstract_type_in_decl,
8665 AbstractVariableType)) {
8666 Var->setInvalidDecl();
8667 return;
8668 }
8669
Douglas Gregor9574af62011-05-21 17:52:48 +00008670 // Check for jumps past the implicit initializer. C++0x
8671 // clarifies that this applies to a "variable with automatic
8672 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008673 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008674 // A program that jumps from a point where a variable with automatic
8675 // storage duration is not in scope to a point where it is in scope is
8676 // ill-formed unless the variable has scalar type, class type with a
8677 // trivial default constructor and a trivial destructor, a cv-qualified
8678 // version of one of these types, or an array of one of the preceding
8679 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008680 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008681 if (const RecordType *Record
8682 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008683 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008684 // Mark the function for further checking even if the looser rules of
8685 // C++11 do not require such checks, so that we can diagnose
8686 // incompatibilities with C++98.
8687 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008688 getCurFunction()->setHasBranchProtectedScope();
8689 }
Douglas Gregore6565622010-02-09 07:26:29 +00008690 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008691
8692 // C++03 [dcl.init]p9:
8693 // If no initializer is specified for an object, and the
8694 // object is of (possibly cv-qualified) non-POD class type (or
8695 // array thereof), the object shall be default-initialized; if
8696 // the object is of const-qualified type, the underlying class
8697 // type shall have a user-declared default
8698 // constructor. Otherwise, if no initializer is specified for
8699 // a non- static object, the object and its subobjects, if
8700 // any, have an indeterminate initial value); if the object
8701 // or any of its subobjects are of const-qualified type, the
8702 // program is ill-formed.
8703 // C++0x [dcl.init]p11:
8704 // If no initializer is specified for an object, the object is
8705 // default-initialized; [...].
8706 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8707 InitializationKind Kind
8708 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008709
8710 InitializationSequence InitSeq(*this, Entity, Kind, None);
8711 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008712 if (Init.isInvalid())
8713 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008714 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008715 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008716 // This is important for template substitution.
8717 Var->setInitStyle(VarDecl::CallInit);
8718 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008719
John McCall8b7fd8f12011-01-19 11:48:09 +00008720 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008721 }
8722}
8723
Richard Smith02e85f32011-04-14 22:09:26 +00008724void Sema::ActOnCXXForRangeDecl(Decl *D) {
8725 VarDecl *VD = dyn_cast<VarDecl>(D);
8726 if (!VD) {
8727 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8728 D->setInvalidDecl();
8729 return;
8730 }
8731
8732 VD->setCXXForRangeDecl(true);
8733
8734 // for-range-declaration cannot be given a storage class specifier.
8735 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008736 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008737 case SC_None:
8738 break;
8739 case SC_Extern:
8740 Error = 0;
8741 break;
8742 case SC_Static:
8743 Error = 1;
8744 break;
8745 case SC_PrivateExtern:
8746 Error = 2;
8747 break;
8748 case SC_Auto:
8749 Error = 3;
8750 break;
8751 case SC_Register:
8752 Error = 4;
8753 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008754 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008755 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008756 }
Richard Smith2316cd82011-09-29 19:11:37 +00008757 if (VD->isConstexpr())
8758 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008759 if (Error != -1) {
8760 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8761 << VD->getDeclName() << Error;
8762 D->setInvalidDecl();
8763 }
8764}
8765
John McCall8b7fd8f12011-01-19 11:48:09 +00008766void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8767 if (var->isInvalidDecl()) return;
8768
John McCall31168b02011-06-15 23:02:42 +00008769 // In ARC, don't allow jumps past the implicit initialization of a
8770 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008771 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008772 var->hasLocalStorage()) {
8773 switch (var->getType().getObjCLifetime()) {
8774 case Qualifiers::OCL_None:
8775 case Qualifiers::OCL_ExplicitNone:
8776 case Qualifiers::OCL_Autoreleasing:
8777 break;
8778
8779 case Qualifiers::OCL_Weak:
8780 case Qualifiers::OCL_Strong:
8781 getCurFunction()->setHasBranchProtectedScope();
8782 break;
8783 }
8784 }
8785
John McCall8a4e2e42014-01-29 08:33:09 +00008786 // Warn about externally-visible variables being defined without a
8787 // prior declaration. We only want to do this for global
8788 // declarations, but we also specifically need to avoid doing it for
8789 // class members because the linkage of an anonymous class can
8790 // change if it's later given a typedef name.
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008791 if (var->isThisDeclarationADefinition() &&
John McCall8a4e2e42014-01-29 08:33:09 +00008792 var->getDeclContext()->getRedeclContext()->isFileContext() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008793 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimek5704e4e2012-12-12 13:26:54 +00008794 getDiagnostics().getDiagnosticLevel(
8795 diag::warn_missing_variable_declarations,
8796 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008797 // Find a previous declaration that's not a definition.
8798 VarDecl *prev = var->getPreviousDecl();
8799 while (prev && prev->isThisDeclarationADefinition())
8800 prev = prev->getPreviousDecl();
8801
8802 if (!prev)
8803 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8804 }
8805
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008806 if (var->getTLSKind() == VarDecl::TLS_Static &&
8807 var->getType().isDestructedType()) {
8808 // GNU C++98 edits for __thread, [basic.start.term]p3:
8809 // The type of an object with thread storage duration shall not
8810 // have a non-trivial destructor.
8811 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8812 if (getLangOpts().CPlusPlus11)
8813 Diag(var->getLocation(), diag::note_use_thread_local);
8814 }
8815
John McCall8b7fd8f12011-01-19 11:48:09 +00008816 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008817 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008818
Richard Smithde63d362012-11-09 23:03:14 +00008819 QualType type = var->getType();
8820 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008821
8822 // __block variables might require us to capture a copy-initializer.
8823 if (var->hasAttr<BlocksAttr>()) {
8824 // It's currently invalid to ever have a __block variable with an
8825 // array type; should we diagnose that here?
8826
8827 // Regardless, we don't want to ignore array nesting when
8828 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00008829 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00008830 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00008831 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00008832 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00008833 ExprResult result
8834 = PerformMoveOrCopyInitialization(
8835 InitializedEntity::InitializeBlock(poi, type, false),
8836 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00008837 if (!result.isInvalid()) {
8838 result = MaybeCreateExprWithCleanups(result);
8839 Expr *init = result.takeAs<Expr>();
8840 Context.setBlockVarCopyInits(var, init);
8841 }
8842 }
8843 }
8844
Richard Smitheda3c842011-11-07 22:16:17 +00008845 Expr *Init = var->getInit();
8846 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00008847 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00008848
Richard Smithbf830092012-10-29 18:26:47 +00008849 if (!var->getDeclContext()->isDependentContext() &&
8850 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008851 if (IsGlobal && !var->isConstexpr() &&
8852 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8853 var->getLocation())
Eli Friedman4c27ac22013-07-16 22:40:53 +00008854 != DiagnosticsEngine::Ignored) {
8855 // Warn about globals which don't have a constant initializer. Don't
8856 // warn about globals with a non-trivial destructor because we already
8857 // warned about them.
8858 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8859 if (!(RD && !RD->hasTrivialDestructor()) &&
8860 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8861 Diag(var->getLocation(), diag::warn_global_constructor)
8862 << Init->getSourceRange();
8863 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00008864
Richard Smithd0b4dd62011-12-19 06:19:21 +00008865 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008866 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00008867 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8868 SourceLocation DiagLoc = var->getLocation();
8869 // If the note doesn't add any useful information other than a source
8870 // location, fold it into the primary diagnostic.
8871 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8872 diag::note_invalid_subexpr_in_const_expr) {
8873 DiagLoc = Notes[0].first;
8874 Notes.clear();
8875 }
8876 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8877 << var << Init->getSourceRange();
8878 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8879 Diag(Notes[I].first, Notes[I].second);
8880 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00008881 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008882 // Check whether the initializer of a const variable of integral or
8883 // enumeration type is an ICE now, since we can't tell whether it was
8884 // initialized by a constant expression if we check later.
8885 var->checkInitIsICE();
8886 }
Richard Smitheda3c842011-11-07 22:16:17 +00008887 }
John McCall8b7fd8f12011-01-19 11:48:09 +00008888
8889 // Require the destructor.
8890 if (const RecordType *recordType = baseType->getAs<RecordType>())
8891 FinalizeVarWithDestructor(var, recordType);
8892}
8893
Richard Smithb2bc2e62011-02-21 20:05:19 +00008894/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8895/// any semantic actions necessary after any initializer has been attached.
8896void
8897Sema::FinalizeDeclaration(Decl *ThisDecl) {
8898 // Note that we are no longer parsing the initializer for this declaration.
8899 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008900
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008901 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00008902 if (!VD)
8903 return;
8904
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00008905 checkAttributesAfterMerging(*this, *VD);
8906
Rafael Espindola87198cd2013-08-16 23:18:50 +00008907 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8908 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00008909 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00008910 VD->dropAttr<UsedAttr>();
8911 }
8912 }
8913
Rafael Espindolad53ffa02013-10-22 21:39:03 +00008914 if (!VD->isInvalidDecl() &&
8915 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8916 if (const VarDecl *Def = VD->getDefinition()) {
8917 if (Def->hasAttr<AliasAttr>()) {
8918 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8919 << VD->getDeclName();
8920 Diag(Def->getLocation(), diag::note_previous_definition);
8921 VD->setInvalidDecl();
8922 }
8923 }
8924 }
8925
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008926 const DeclContext *DC = VD->getDeclContext();
8927 // If there's a #pragma GCC visibility in scope, and this isn't a class
8928 // member, set the visibility of this variable.
John McCall8a4e2e42014-01-29 08:33:09 +00008929 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008930 AddPushedVisibilityAttribute(VD);
8931
Rafael Espindolad2ecc132013-01-03 04:29:20 +00008932 if (VD->isFileVarDecl())
8933 MarkUnusedFileScopedDecl(VD);
8934
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008935 // Now we have parsed the initializer and can update the table of magic
8936 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00008937 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8938 !VD->getType()->isIntegralOrEnumerationType())
8939 return;
8940
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00008941 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
Rafael Espindola60470f12013-01-03 04:05:19 +00008942 const Expr *MagicValueExpr = VD->getInit();
8943 if (!MagicValueExpr) {
8944 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008945 }
Rafael Espindola60470f12013-01-03 04:05:19 +00008946 llvm::APSInt MagicValueInt;
8947 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8948 Diag(I->getRange().getBegin(),
8949 diag::err_type_tag_for_datatype_not_ice)
8950 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8951 continue;
8952 }
8953 if (MagicValueInt.getActiveBits() > 64) {
8954 Diag(I->getRange().getBegin(),
8955 diag::err_type_tag_for_datatype_too_large)
8956 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8957 continue;
8958 }
8959 uint64_t MagicValue = MagicValueInt.getZExtValue();
8960 RegisterTypeTagForDatatype(I->getArgumentKind(),
8961 MagicValue,
8962 I->getMatchingCType(),
8963 I->getLayoutCompatible(),
8964 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008965 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00008966}
8967
Rafael Espindolaab417692013-07-09 12:05:01 +00008968Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8969 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008970 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008971
8972 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00008973 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008974
David Majnemer50ce8352013-09-17 23:57:10 +00008975 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00008976 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00008977 if (Decl *D = Group[i]) {
8978 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8979 if (!FirstDeclaratorInGroup)
8980 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00008981 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00008982 }
Richard Smith2abf6762011-02-23 00:37:57 +00008983
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008984 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00008985 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
David Majnemer2206bf52014-03-05 08:57:59 +00008986 HandleTagNumbering(*this, Tag, S);
David Majnemer50ce8352013-09-17 23:57:10 +00008987 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8988 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8989 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008990 }
David Blaikie095deba2012-11-14 01:52:05 +00008991
Rafael Espindolaab417692013-07-09 12:05:01 +00008992 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00008993}
8994
8995/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8996/// group, performing any necessary semantic checking.
8997Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00008998Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00008999 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00009000 // C++0x [dcl.spec.auto]p7:
9001 // If the type deduced for the template parameter U is not the same in each
9002 // deduction, the program is ill-formed.
9003 // FIXME: When initializer-list support is added, a distinction is needed
9004 // between the deduced type U and the deduced type which 'auto' stands for.
9005 // auto a = 0, b = { 1, 2, 3 };
9006 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009007 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009008 QualType Deduced;
9009 CanQualType DeducedCanon;
9010 VarDecl *DeducedDecl = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009011 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009012 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9013 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009014 // Don't reissue diagnostics when instantiating a template.
9015 if (AT && D->isInvalidDecl())
9016 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009017 QualType U = AT ? AT->getDeducedType() : QualType();
9018 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009019 CanQualType UCanon = Context.getCanonicalType(U);
9020 if (Deduced.isNull()) {
9021 Deduced = U;
9022 DeducedCanon = UCanon;
9023 DeducedDecl = D;
9024 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009025 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9026 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009027 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009028 << Deduced << DeducedDecl->getDeclName()
9029 << U << D->getDeclName()
9030 << DeducedDecl->getInit()->getSourceRange()
9031 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009032 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009033 break;
9034 }
9035 }
9036 }
9037 }
9038 }
9039
Rafael Espindolaab417692013-07-09 12:05:01 +00009040 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009041
Rafael Espindolaab417692013-07-09 12:05:01 +00009042 return DeclGroupPtrTy::make(
9043 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009044}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009045
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009046void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009047 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009048}
9049
Rafael Espindolaab417692013-07-09 12:05:01 +00009050void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009051 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009052 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009053 return;
9054
9055 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9056 Group[0]->getLocation())
9057 == DiagnosticsEngine::Ignored)
9058 return;
9059
Rafael Espindolaab417692013-07-09 12:05:01 +00009060 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009061 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009062 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009063 // additional declaration references:
9064 // 'typedef struct S {} S;'
9065 // 'typedef struct S *S;'
9066 // 'struct S *pS;'
9067 // FinalizeDeclaratorGroup adds these as separate declarations.
9068 Decl *MaybeTagDecl = Group[0];
9069 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009070 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009071 }
9072 }
9073
9074 // See if there are any new comments that are not attached to a decl.
9075 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9076 if (!Comments.empty() &&
9077 !Comments.back()->isAttached()) {
9078 // There is at least one comment that not attached to a decl.
9079 // Maybe it should be attached to one of these decls?
9080 //
9081 // Note that this way we pick up not only comments that precede the
9082 // declaration, but also comments that *follow* the declaration -- thanks to
9083 // the lookahead in the lexer: we've consumed the semicolon and looked
9084 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009085 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009086 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009087 }
9088}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009089
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009090/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9091/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009092Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009093 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009094
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009095 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009096
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009097 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009098 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009099 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009100 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009101 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009102 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9103 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009104 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009105 Diag(DS.getStorageClassSpecLoc(),
9106 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009107 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009108 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009109
Richard Smithb4a9e862013-04-12 22:46:28 +00009110 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9111 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9112 << DeclSpec::getSpecifierName(TSCS);
9113 if (DS.isConstexprSpecified())
9114 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009115 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009116
Richard Smithb4a9e862013-04-12 22:46:28 +00009117 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009118
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009119 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009120 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009121
David Blaikiebbafb8a2012-03-11 07:00:24 +00009122 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009123 // Check that there are no default arguments inside the type of this
9124 // parameter.
9125 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009126
9127 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9128 if (D.getCXXScopeSpec().isSet()) {
9129 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9130 << D.getCXXScopeSpec().getRange();
9131 D.getCXXScopeSpec().clear();
9132 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009133 }
9134
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009135 // Ensure we have a valid name
9136 IdentifierInfo *II = 0;
9137 if (D.hasName()) {
9138 II = D.getIdentifier();
9139 if (!II) {
9140 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009141 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009142 D.setInvalidType(true);
9143 }
9144 }
9145
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009146 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009147 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009148 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9149 ForRedeclaration);
9150 LookupName(R, S);
9151 if (R.isSingleResult()) {
9152 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009153 if (PrevDecl->isTemplateParameter()) {
9154 // Maybe we will complain about the shadowed template parameter.
9155 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9156 // Just pretend that we didn't see the previous declaration.
9157 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00009158 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009159 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009160 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009161
Chris Lattnerd9773512009-01-21 02:38:50 +00009162 // Recover by removing the name
9163 II = 0;
9164 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009165 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009166 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009167 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009168 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009169
John McCallf7b2fb52010-01-22 00:28:27 +00009170 // Temporarily put parameter variables in the translation unit, not
9171 // the enclosing context. This prevents them from accidentally
9172 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009173 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009174 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009175 D.getIdentifierLoc(), II,
9176 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009177 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009178
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009179 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009180 New->setInvalidDecl();
9181
9182 assert(S->isFunctionPrototypeScope());
9183 assert(S->getFunctionPrototypeDepth() >= 1);
9184 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9185 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009186
Douglas Gregor91f84212008-12-11 16:49:14 +00009187 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009188 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009189 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009190 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009191
Douglas Gregor758a8692009-06-17 21:51:59 +00009192 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009193
Douglas Gregor41866812011-09-12 18:37:38 +00009194 if (D.getDeclSpec().isModulePrivateSpecified())
9195 Diag(New->getLocation(), diag::err_module_private_local)
9196 << 1 << New->getDeclName()
9197 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9198 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9199
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009200 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009201 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9202 }
John McCall48871652010-08-21 09:40:31 +00009203 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009204}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009205
John McCalla3ccba02010-06-04 11:21:44 +00009206/// \brief Synthesizes a variable for a parameter arising from a
9207/// typedef.
9208ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9209 SourceLocation Loc,
9210 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009211 /* FIXME: setting StartLoc == Loc.
9212 Would it be worth to modify callers so as to provide proper source
9213 location for the unnamed parameters, embedding the parameter's type? */
9214 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00009215 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009216 SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00009217 Param->setImplicit();
9218 return Param;
9219}
9220
John McCallc5990642010-08-24 09:05:15 +00009221void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9222 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009223 // Don't diagnose unused-parameter errors in template instantiations; we
9224 // will already have done so in the template itself.
9225 if (!ActiveTemplateInstantiations.empty())
9226 return;
9227
9228 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009229 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009230 !(*Param)->hasAttr<UnusedAttr>()) {
9231 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9232 << (*Param)->getDeclName();
9233 }
9234 }
9235}
9236
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009237void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9238 ParmVarDecl * const *ParamEnd,
9239 QualType ReturnTy,
9240 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009241 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009242 return;
9243
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009244 // Warn if the return value is pass-by-value and larger than the specified
9245 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009246 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009247 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009248 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009249 Diag(D->getLocation(), diag::warn_return_value_size)
9250 << D->getDeclName() << Size;
9251 }
9252
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009253 // Warn if any parameter is pass-by-value and larger than the specified
9254 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009255 for (; Param != ParamEnd; ++Param) {
9256 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009257 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009258 continue;
9259 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009260 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009261 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9262 << (*Param)->getDeclName() << Size;
9263 }
9264}
9265
Abramo Bagnaradff19302011-03-08 08:55:46 +00009266ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9267 SourceLocation NameLoc, IdentifierInfo *Name,
9268 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009269 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009270 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009271 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009272 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009273 T->isObjCLifetimeType()) {
9274
9275 Qualifiers::ObjCLifetime lifetime;
9276
9277 // Special cases for arrays:
9278 // - if it's const, use __unsafe_unretained
9279 // - otherwise, it's an error
9280 if (T->isArrayType()) {
9281 if (!T.isConstQualified()) {
9282 DelayedDiagnostics.add(
9283 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009284 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009285 }
9286 lifetime = Qualifiers::OCL_ExplicitNone;
9287 } else {
9288 lifetime = T->getObjCARCImplicitLifetime();
9289 }
9290 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009291 }
9292
Abramo Bagnaradff19302011-03-08 08:55:46 +00009293 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009294 Context.getAdjustedParameterType(T),
9295 TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009296 StorageClass, 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00009297
9298 // Parameters can not be abstract class types.
9299 // For record types, this is done by the AbstractClassUsageDiagnoser once
9300 // the class has been completely parsed.
9301 if (!CurContext->isRecord() &&
9302 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9303 AbstractParamType))
9304 New->setInvalidDecl();
9305
9306 // Parameter declarators cannot be interface types. All ObjC objects are
9307 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009308 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009309 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009310 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009311 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009312 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009313 T = Context.getObjCObjectPointerType(T);
9314 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009315 }
9316
9317 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9318 // duration shall not be qualified by an address-space qualifier."
9319 // Since all parameters have automatic store duration, they can not have
9320 // an address space.
9321 if (T.getAddressSpace() != 0) {
9322 Diag(NameLoc, diag::err_arg_with_address_space);
9323 New->setInvalidDecl();
9324 }
9325
9326 return New;
9327}
9328
Douglas Gregor170512f2009-04-01 23:51:29 +00009329void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9330 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009331 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009332
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009333 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9334 // for a K&R function.
9335 if (!FTI.hasPrototype) {
Alp Tokerc5350722014-02-26 22:27:52 +00009336 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009337 --i;
Alp Tokerc5350722014-02-26 22:27:52 +00009338 if (FTI.Params[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009339 SmallString<256> Code;
Alp Tokerc5350722014-02-26 22:27:52 +00009340 llvm::raw_svector_ostream(Code)
9341 << " int " << FTI.Params[i].Ident->getName() << ";\n";
9342 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9343 << FTI.Params[i].Ident
9344 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009345
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009346 // Implicitly declare the argument as type 'int' for lack of a better
9347 // type.
John McCall084e83d2011-03-24 11:26:52 +00009348 AttributeFactory attrs;
9349 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009350 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009351 unsigned DiagID; // unused
Alp Tokerc5350722014-02-26 22:27:52 +00009352 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9353 DiagID, Context.getPrintingPolicy());
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009354 // Use the identifier location for the type source range.
Alp Tokerc5350722014-02-26 22:27:52 +00009355 DS.SetRangeStart(FTI.Params[i].IdentLoc);
9356 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009357 Declarator ParamD(DS, Declarator::KNRTypeListContext);
Alp Tokerc5350722014-02-26 22:27:52 +00009358 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9359 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009360 }
9361 }
Mike Stump11289f42009-09-09 15:08:12 +00009362 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009363}
9364
Richard Smith79a52e52012-04-17 22:30:01 +00009365Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00009366 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009367 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009368 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009369
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009370 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009371 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009372 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009373}
9374
Anders Carlsson2a45e402012-12-18 01:29:20 +00009375static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9376 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009377 // Don't warn about invalid declarations.
9378 if (FD->isInvalidDecl())
9379 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009380
Anders Carlsson31c7e882009-12-09 03:30:09 +00009381 // Or declarations that aren't global.
9382 if (!FD->isGlobal())
9383 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009384
Anders Carlsson31c7e882009-12-09 03:30:09 +00009385 // Don't warn about C++ member functions.
9386 if (isa<CXXMethodDecl>(FD))
9387 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009388
Anders Carlsson31c7e882009-12-09 03:30:09 +00009389 // Don't warn about 'main'.
9390 if (FD->isMain())
9391 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009392
Anders Carlsson31c7e882009-12-09 03:30:09 +00009393 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009394 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009395 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009396
9397 // Don't warn about function templates.
9398 if (FD->getDescribedFunctionTemplate())
9399 return false;
9400
9401 // Don't warn about function template specializations.
9402 if (FD->isFunctionTemplateSpecialization())
9403 return false;
9404
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009405 // Don't warn for OpenCL kernels.
9406 if (FD->hasAttr<OpenCLKernelAttr>())
9407 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009408
Anders Carlsson31c7e882009-12-09 03:30:09 +00009409 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009410 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9411 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009412 // Ignore any declarations that occur in function or method
9413 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009414 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009415 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009416
Anders Carlsson31c7e882009-12-09 03:30:09 +00009417 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009418 if (FD->getNumParams() == 0)
9419 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009420 break;
9421 }
Richard Smith541b38b2013-09-20 01:15:31 +00009422
Anders Carlsson31c7e882009-12-09 03:30:09 +00009423 return MissingPrototype;
9424}
9425
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009426void
9427Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9428 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009429 // Don't complain if we're in GNU89 mode and the previous definition
9430 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009431 const FunctionDecl *Definition = EffectiveDefinition;
9432 if (!Definition)
9433 if (!FD->isDefined(Definition))
9434 return;
9435
9436 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009437 return;
9438
9439 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9440 Definition->getStorageClass() == SC_Extern)
9441 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009442 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009443 else
9444 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9445
9446 Diag(Definition->getLocation(), diag::note_previous_definition);
9447 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009448}
Faisal Valia17d19f2013-11-07 05:17:06 +00009449
9450
Faisal Valic1a6dc42013-10-23 16:10:50 +00009451static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9452 Sema &S) {
9453 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009454
9455 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009456 LSI->CallOperator = CallOperator;
9457 LSI->Lambda = LambdaClass;
Alp Toker314cc812014-01-25 16:55:45 +00009458 LSI->ReturnType = CallOperator->getReturnType();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009459 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9460
9461 if (LCD == LCD_None)
9462 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9463 else if (LCD == LCD_ByCopy)
9464 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9465 else if (LCD == LCD_ByRef)
9466 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9467 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9468
9469 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9470 LSI->Mutable = !CallOperator->isConst();
9471
Faisal Valia17d19f2013-11-07 05:17:06 +00009472 // Add the captures to the LSI so they can be noted as already
9473 // captured within tryCaptureVar.
9474 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9475 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9476 if (C->capturesVariable()) {
9477 VarDecl *VD = C->getCapturedVar();
9478 if (VD->isInitCapture())
9479 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9480 QualType CaptureType = VD->getType();
9481 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9482 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9483 /*RefersToEnclosingLocal*/true, C->getLocation(),
9484 /*EllipsisLoc*/C->isPackExpansion()
9485 ? C->getEllipsisLoc() : SourceLocation(),
9486 CaptureType, /*Expr*/ 0);
9487
9488 } else if (C->capturesThis()) {
9489 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9490 S.getCurrentThisType(), /*Expr*/ 0);
9491 }
9492 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009493}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009494
John McCall48871652010-08-21 09:40:31 +00009495Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009496 // Clear the last template instantiation error context.
9497 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9498
Douglas Gregor17a7c122009-06-24 00:54:41 +00009499 if (!D)
9500 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009501 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009502
John McCall48871652010-08-21 09:40:31 +00009503 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009504 FD = FunTmpl->getTemplatedDecl();
9505 else
John McCall48871652010-08-21 09:40:31 +00009506 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009507 // If we are instantiating a generic lambda call operator, push
9508 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009509 // that's already been calculated (ActOnLambdaExpr) to prime the current
9510 // LambdaScopeInfo.
9511 // When the template operator is being specialized, the LambdaScopeInfo,
9512 // has to be properly restored so that tryCaptureVariable doesn't try
9513 // and capture any new variables. In addition when calculating potential
9514 // captures during transformation of nested lambdas, it is necessary to
9515 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009516 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009517 assert(ActiveTemplateInstantiations.size() &&
9518 "There should be an active template instantiation on the stack "
9519 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009520 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009521 }
9522 else
9523 // Enter a new function scope
9524 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009525
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009526 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009527 if (!FD->isLateTemplateParsed())
9528 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009529
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009530 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009531 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009532 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9533 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009534 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009535 FD->setInvalidDecl();
9536 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009537 }
9538
Eli Friedman9ad72442009-03-04 07:30:59 +00009539 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009540 // (C99 6.9.1p3, C++ [dcl.fct]p6).
Alp Toker314cc812014-01-25 16:55:45 +00009541 QualType ResultType = FD->getReturnType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00009542 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009543 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009544 RequireCompleteType(FD->getLocation(), ResultType,
9545 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009546 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009547
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009548 // GNU warning -Wmissing-prototypes:
9549 // Warn if a global function is defined without a previous
9550 // prototype declaration. This warning is issued even if the
9551 // definition itself provides a prototype. The aim is to detect
9552 // global functions that fail to be declared in header files.
Anders Carlsson2a45e402012-12-18 01:29:20 +00009553 const FunctionDecl *PossibleZeroParamPrototype = 0;
9554 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009555 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009556
Anders Carlsson2a45e402012-12-18 01:29:20 +00009557 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009558 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009559 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009560 if (TypeSourceInfo *TI =
9561 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9562 TypeLoc TL = TI->getTypeLoc();
9563 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9564 Diag(PossibleZeroParamPrototype->getLocation(),
9565 diag::note_declaration_not_a_prototype)
9566 << PossibleZeroParamPrototype
9567 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9568 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009569 }
9570 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009571
Douglas Gregor67da0d92009-05-15 17:59:04 +00009572 if (FnBodyScope)
9573 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009574
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009575 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009576 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9577 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009578
9579 // Introduce our parameters into the function scope
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00009580 for (auto Param : FD->params()) {
Douglas Gregorc72e6452009-01-09 18:51:29 +00009581 Param->setOwningFunction(FD);
9582
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009583 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009584 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009585 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009586
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009587 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009588 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009589 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009590
James Molloy6f8780b2012-02-29 10:24:19 +00009591 // If we had any tags defined in the function prototype,
9592 // introduce them into the function scope.
9593 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009594 for (ArrayRef<NamedDecl *>::iterator
9595 I = FD->getDeclsInPrototypeScope().begin(),
9596 E = FD->getDeclsInPrototypeScope().end();
9597 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009598 NamedDecl *D = *I;
9599
9600 // Some of these decls (like enums) may have been pinned to the translation unit
9601 // for lack of a real context earlier. If so, remove from the translation unit
9602 // and reattach to the current context.
9603 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9604 // Is the decl actually in the context?
Aaron Ballman629afae2014-03-07 19:56:05 +00009605 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
9606 if (DI == D) {
James Molloy6f8780b2012-02-29 10:24:19 +00009607 Context.getTranslationUnitDecl()->removeDecl(D);
9608 break;
9609 }
9610 }
9611 // Either way, reassign the lexical decl context to our FunctionDecl.
9612 D->setLexicalDeclContext(CurContext);
9613 }
9614
9615 // If the decl has a non-null name, make accessible in the current scope.
9616 if (!D->getName().empty())
9617 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9618
9619 // Similarly, dive into enums and fish their constants out, making them
9620 // accessible in this scope.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00009621 if (auto *ED = dyn_cast<EnumDecl>(D)) {
9622 for (auto *EI : ED->enumerators())
9623 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009624 }
9625 }
9626 }
9627
Richard Smith79a52e52012-04-17 22:30:01 +00009628 // Ensure that the function's exception specification is instantiated.
9629 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9630 ResolveExceptionSpec(D->getLocation(), FPT);
9631
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009632 // Checking attributes of current function definition
9633 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009634 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
Aaron Ballman9ead1242013-12-19 02:39:40 +00009635 if (DA && (!FD->hasAttr<DLLExportAttr>())) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009636 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00009637 // Microsoft accepts dllimport for functions defined within class scope.
9638 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00009639 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009640 Diag(FD->getLocation(),
9641 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
Aaron Ballman3e424b52013-12-26 18:30:57 +00009642 << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009643 FD->setInvalidDecl();
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009644 return D;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00009645 }
9646
9647 // Visual C++ appears to not think this is an issue, so only issue
9648 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00009649 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009650 // If a symbol previously declared dllimport is later defined, the
9651 // attribute is ignored in subsequent references, and a warning is
9652 // emitted.
9653 Diag(FD->getLocation(),
9654 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Aaron Ballman44ebc072014-01-02 22:29:41 +00009655 << FD << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009656 }
9657 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009658 // We want to attach documentation to original Decl (which might be
9659 // a function template).
9660 ActOnDocumentableDecl(D);
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009661 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009662}
9663
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009664/// \brief Given the set of return statements within a function body,
9665/// compute the variables that are subject to the named return value
9666/// optimization.
9667///
9668/// Each of the variables that is subject to the named return value
9669/// optimization will be marked as NRVO variables in the AST, and any
9670/// return statement that has a marked NRVO variable as its NRVO candidate can
9671/// use the named return value optimization.
9672///
9673/// This function applies a very simplistic algorithm for NRVO: if every return
9674/// statement in the function has the same NRVO candidate, that candidate is
9675/// the NRVO variable.
9676///
9677/// FIXME: Employ a smarter algorithm that accounts for multiple return
9678/// statements and the lifetimes of the NRVO candidates. We should be able to
9679/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00009680void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009681 ReturnStmt **Returns = Scope->Returns.data();
9682
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009683 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00009684 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009685 if (!Returns[I]->getNRVOCandidate())
9686 return;
9687
9688 if (!NRVOCandidate)
9689 NRVOCandidate = Returns[I]->getNRVOCandidate();
9690 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9691 return;
9692 }
9693
9694 if (NRVOCandidate)
9695 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9696}
9697
Richard Smith8e6002f2014-03-12 23:14:33 +00009698bool Sema::canDelayFunctionBody(const Declarator &D) {
9699 // We can't delay parsing the body of a constexpr function template (yet).
9700 if (D.getDeclSpec().isConstexprSpecified())
9701 return false;
9702
9703 // We can't delay parsing the body of a function template with a deduced
9704 // return type (yet).
9705 if (D.getDeclSpec().containsPlaceholderType()) {
9706 // If the placeholder introduces a non-deduced trailing return type,
9707 // we can still delay parsing it.
9708 if (D.getNumTypeObjects()) {
9709 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
9710 if (Outer.Kind == DeclaratorChunk::Function &&
9711 Outer.Fun.hasTrailingReturnType()) {
9712 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
9713 return Ty.isNull() || !Ty->isUndeducedType();
9714 }
9715 }
9716 return false;
9717 }
9718
9719 return true;
9720}
9721
Richard Smith1ab34b32012-11-19 21:13:18 +00009722bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith1ab34b32012-11-19 21:13:18 +00009723 // We cannot skip the body of a function (or function template) which is
9724 // constexpr, since we may need to evaluate its body in order to parse the
9725 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009726 // We cannot skip the body of a function with an undeduced return type,
9727 // because any callers of that function need to know the type.
Alp Tokera2794f92014-01-22 07:29:52 +00009728 if (const FunctionDecl *FD = D->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00009729 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
Alp Tokera2794f92014-01-22 07:29:52 +00009730 return false;
9731 return Consumer.shouldSkipFunctionBody(D);
Richard Smith1ab34b32012-11-19 21:13:18 +00009732}
9733
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009734Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009735 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009736 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009737 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009738 MD->setHasSkippedBody();
9739 return ActOnFinishFunctionBody(Decl, 0);
9740}
9741
John McCallfaf5fb42010-08-26 23:41:50 +00009742Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009743 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009744}
9745
John McCallb268a282010-08-23 23:25:46 +00009746Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9747 bool IsInstantiation) {
Alp Tokera2794f92014-01-22 07:29:52 +00009748 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009749
Ted Kremenek0b405322010-03-23 00:13:23 +00009750 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00009751 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00009752
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009753 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009754 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009755
Richard Smith7500ab22013-05-10 04:31:10 +00009756 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
Alp Toker314cc812014-01-25 16:55:45 +00009757 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009758 // If the function has a deduced result type but contains no 'return'
9759 // statements, the result type as written must be exactly 'auto', and
9760 // the deduced result type is 'void'.
Alp Toker314cc812014-01-25 16:55:45 +00009761 if (!FD->getReturnType()->getAs<AutoType>()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009762 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
Alp Toker314cc812014-01-25 16:55:45 +00009763 << FD->getReturnType();
Richard Smith7500ab22013-05-10 04:31:10 +00009764 FD->setInvalidDecl();
9765 } else {
9766 // Substitute 'void' for the 'auto' in the type.
9767 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00009768 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith7500ab22013-05-10 04:31:10 +00009769 Context.adjustDeducedFunctionResultType(
9770 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009771 }
9772 }
9773
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009774 // The only way to be included in UndefinedButUsed is if there is an
9775 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009776 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009777 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009778 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009779 UndefinedButUsed.erase(FD);
9780 else if (FD->isInlined() &&
9781 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9782 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9783 UndefinedButUsed.erase(FD);
9784 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009785
John McCall5ed3caf2012-02-14 19:50:52 +00009786 // If the function implicitly returns zero (like 'main') or is naked,
9787 // don't complain about missing return statements.
9788 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009789 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00009790
Francois Pichet3abc9b82011-05-11 02:14:46 +00009791 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +00009792 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +00009793 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +00009794 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9795
Douglas Gregor88d292c2010-05-13 16:44:06 +00009796 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009797 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009798 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009799 FD->getReturnType(), FD);
9800
Douglas Gregor88d292c2010-05-13 16:44:06 +00009801 // If this is a constructor, we need a vtable.
9802 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9803 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009804
Jordan Rosed39e5f12012-07-02 21:19:23 +00009805 // Try to apply the named return value optimization. We have to check
9806 // if we can do this here because lambdas keep return statements around
9807 // to deduce an implicit return type.
Alp Toker314cc812014-01-25 16:55:45 +00009808 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
Jordan Rosed39e5f12012-07-02 21:19:23 +00009809 !FD->isDependentContext())
9810 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00009811 }
9812
Douglas Gregor21f46922012-02-08 20:17:14 +00009813 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9814 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00009815 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00009816 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00009817 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009818 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009819 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009820 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009821 MD->getReturnType(), MD);
9822
Douglas Gregore3f3ea02011-09-06 20:33:37 +00009823 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00009824 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009825 }
Jordan Rose2afd6612012-10-19 16:05:26 +00009826 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00009827 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9828 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00009829 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00009830 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009831 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9832 const ObjCMethodDecl *InitMethod = 0;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00009833 bool isDesignated =
9834 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009835 assert(isDesignated && InitMethod);
9836 (void)isDesignated;
9837 Diag(MD->getLocation(),
9838 diag::warn_objc_designated_init_missing_super_call);
9839 Diag(InitMethod->getLocation(),
9840 diag::note_objc_designated_init_marked_here);
9841 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9842 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009843 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9844 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9845 getCurFunction()->ObjCWarnForNoInitDelegation = false;
9846 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009847 } else {
John McCall48871652010-08-21 09:40:31 +00009848 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009849 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009850
Jordan Rose2afd6612012-10-19 16:05:26 +00009851 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009852 "This should only be set for ObjC methods, which should have been "
9853 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00009854
Chris Lattnere2473062007-05-28 06:28:18 +00009855 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00009856 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009857 // C++ constructors that have function-try-blocks can't have return
9858 // statements in the handlers of that block. (C++ [except.handle]p14)
9859 // Verify this.
9860 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9861 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9862
Richard Smithdef8bdb2011-08-12 18:44:32 +00009863 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00009864 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00009865 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009866 !hasAnyUnrecoverableErrorsInThisFunction() &&
9867 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00009868 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00009869
John McCalldeb646e2010-08-04 01:04:25 +00009870 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9871 if (!Destructor->getParent()->isDependentType())
9872 CheckDestructor(Destructor);
9873
John McCalla6309952010-03-16 21:39:52 +00009874 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9875 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00009876 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00009877
9878 // If any errors have occurred, clear out any temporaries that may have
9879 // been leftover. This ensures that these temporaries won't be picked up for
9880 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00009881 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00009882 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00009883 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00009884 }
9885 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9886 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00009887 // Since the body is valid, issue any analysis-based warnings that are
9888 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00009889 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00009890 }
9891
Richard Smith3607ffe2012-02-13 03:54:03 +00009892 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9893 (!CheckConstexprFunctionDecl(FD) ||
9894 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00009895 FD->setInvalidDecl();
9896
John McCall28fc7092011-11-10 05:35:25 +00009897 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00009898 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00009899 assert(MaybeODRUseExprs.empty() &&
9900 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00009901 }
9902
John McCalle99d5f32010-03-25 22:08:03 +00009903 if (!IsInstantiation)
9904 PopDeclContext();
9905
Eli Friedman71c80552012-01-05 03:35:19 +00009906 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +00009907 // If any errors have occurred, clear out any temporaries that may have
9908 // been leftover. This ensures that these temporaries won't be picked up for
9909 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00009910 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00009911 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00009912 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00009913
John McCall48871652010-08-21 09:40:31 +00009914 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00009915}
9916
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009917
9918/// When we finish delayed parsing of an attribute, we must attach it to the
9919/// relevant Decl.
9920void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9921 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00009922 // Always attach attributes to the underlying decl.
9923 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9924 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00009925 ProcessDeclAttributeList(S, D, Attrs.getList());
9926
9927 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9928 if (Method->isStatic())
9929 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009930}
9931
9932
Chris Lattnerac18be92006-11-20 06:49:47 +00009933/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9934/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00009935NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00009936 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009937 // Before we produce a declaration for an implicitly defined
9938 // function, see whether there was a locally-scoped declaration of
9939 // this name as a function or variable. If so, use that
9940 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +00009941 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9942 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9943 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9944 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009945 }
9946
Chris Lattner00e26072008-05-05 21:18:06 +00009947 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00009948 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00009949 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00009950 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009951 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00009952 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00009953 else
Hans Wennborg70a13242011-12-08 15:56:07 +00009954 diag_id = diag::warn_implicit_function_decl;
9955 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00009956
Hans Wennborg70a13242011-12-08 15:56:07 +00009957 // Because typo correction is expensive, only do it if the implicit
9958 // function declaration is going to be treated as an error.
9959 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9960 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00009961 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00009962 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smithf9b15102013-08-17 00:46:16 +00009963 LookupOrdinaryName, S, 0, Validator)))
9964 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9965 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +00009966 }
9967
Chris Lattnerac18be92006-11-20 06:49:47 +00009968 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00009969 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00009970 AttributeFactory attrFactory;
9971 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00009972 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00009973 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
9974 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009975 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00009976 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009977 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +00009978 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009979 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9980 /*IsAmbiguous=*/false,
9981 /*RParenLoc=*/NoLoc,
9982 /*ArgInfo=*/0,
9983 /*NumArgs=*/0,
9984 /*EllipsisLoc=*/NoLoc,
9985 /*RParenLoc=*/NoLoc,
9986 /*TypeQuals=*/0,
9987 /*RefQualifierIsLvalueRef=*/true,
9988 /*RefQualifierLoc=*/NoLoc,
9989 /*ConstQualifierLoc=*/NoLoc,
9990 /*VolatileQualifierLoc=*/NoLoc,
9991 /*MutableLoc=*/NoLoc,
9992 EST_None,
9993 /*ESpecLoc=*/NoLoc,
9994 /*Exceptions=*/0,
9995 /*ExceptionRanges=*/0,
9996 /*NumExceptions=*/0,
9997 /*NoexceptExpr=*/0,
9998 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00009999 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010000 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +000010001 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010002
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010003 // Insert this function into translation-unit scope.
10004
10005 DeclContext *PrevDC = CurContext;
10006 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010007
Jordan Rosed03d99d2013-03-05 01:27:54 +000010008 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010009 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010010
10011 CurContext = PrevDC;
10012
Douglas Gregore711f702009-02-14 18:57:46 +000010013 AddKnownFunctionAttributes(FD);
10014
Steve Naroff3913ea42008-04-04 14:32:09 +000010015 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010016}
10017
Douglas Gregore711f702009-02-14 18:57:46 +000010018/// \brief Adds any function attributes that we know a priori based on
10019/// the declaration of this function.
10020///
10021/// These attributes can apply both to implicitly-declared builtins
10022/// (like __builtin___printf_chk) or to library-declared functions
10023/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010024///
10025/// We need to check for duplicate attributes both here and where user-written
10026/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010027void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10028 if (FD->isInvalidDecl())
10029 return;
10030
10031 // If this is a built-in function, map its builtin attributes to
10032 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010033 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010034 // Handle printf-formatting attributes.
10035 unsigned FormatIdx;
10036 bool HasVAListArg;
10037 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010038 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010039 const char *fmt = "printf";
10040 unsigned int NumParams = FD->getNumParams();
10041 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10042 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10043 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010044 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010045 &Context.Idents.get(fmt),
10046 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010047 HasVAListArg ? 0 : FormatIdx+2,
10048 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010049 }
Douglas Gregore711f702009-02-14 18:57:46 +000010050 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010051 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10052 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010053 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010054 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010055 &Context.Idents.get("scanf"),
10056 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010057 HasVAListArg ? 0 : FormatIdx+2,
10058 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010059 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010060
10061 // Mark const if we don't care about errno and that is the only
10062 // thing preventing the function from being const. This allows
10063 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010064 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010065 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010066 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010067 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010068 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010069
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010070 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010071 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010072 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10073 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010074 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010075 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010076 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010077 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010078 }
10079
10080 IdentifierInfo *Name = FD->getIdentifier();
10081 if (!Name)
10082 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010083 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010084 FD->getDeclContext()->isTranslationUnit()) ||
10085 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010086 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010087 LinkageSpecDecl::lang_c)) {
10088 // Okay: this could be a libc/libm/Objective-C function we know
10089 // about.
10090 } else
10091 return;
10092
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010093 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010094 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010095 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010096 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010097 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010098 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010099 Name->isStr("vasprintf") ? 0 : 3,
10100 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010101 }
Jordan Rose742c6072012-08-08 21:17:31 +000010102
10103 if (Name->isStr("__CFStringMakeConstantString")) {
10104 // We already have a __builtin___CFStringMakeConstantString,
10105 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010106 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010107 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10108 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010109 }
Douglas Gregore711f702009-02-14 18:57:46 +000010110}
Chris Lattner302b4be2006-11-19 02:31:38 +000010111
John McCall703a3f82009-10-24 08:00:42 +000010112TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010113 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010114 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010115 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010116
John McCallbcd03502009-12-07 02:54:59 +000010117 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010118 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010119 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010120 }
10121
Chris Lattner18b19622007-01-22 07:39:13 +000010122 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010123 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010124 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010125 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010126 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010127 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010128
John McCall04fcd0d2011-02-01 08:20:08 +000010129 // Bail out immediately if we have an invalid declaration.
10130 if (D.isInvalidType()) {
10131 NewTD->setInvalidDecl();
10132 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010133 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010134
Douglas Gregor41866812011-09-12 18:37:38 +000010135 if (D.getDeclSpec().isModulePrivateSpecified()) {
10136 if (CurContext->isFunctionOrMethod())
10137 Diag(NewTD->getLocation(), diag::err_module_private_local)
10138 << 2 << NewTD->getDeclName()
10139 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10140 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10141 else
10142 NewTD->setModulePrivate();
10143 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010144
John McCall04fcd0d2011-02-01 08:20:08 +000010145 // C++ [dcl.typedef]p8:
10146 // If the typedef declaration defines an unnamed class (or
10147 // enum), the first typedef-name declared by the declaration
10148 // to be that class type (or enum type) is used to denote the
10149 // class type (or enum type) for linkage purposes only.
10150 // We need to check whether the type was declared in the declaration.
10151 switch (D.getDeclSpec().getTypeSpecType()) {
10152 case TST_enum:
10153 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010154 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010155 case TST_union:
10156 case TST_class: {
10157 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10158
10159 // Do nothing if the tag is not anonymous or already has an
10160 // associated typedef (from an earlier typedef in this decl group).
10161 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010162 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010163
10164 // A well-formed anonymous tag must always be a TUK_Definition.
10165 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10166
10167 // The type must match the tag exactly; no qualifiers allowed.
10168 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10169 break;
10170
John McCall2575d882014-01-30 01:12:53 +000010171 // If we've already computed linkage for the anonymous tag, then
10172 // adding a typedef name for the anonymous decl can change that
10173 // linkage, which might be a serious problem. Diagnose this as
10174 // unsupported and ignore the typedef name. TODO: we should
10175 // pursue this as a language defect and establish a formal rule
10176 // for how to handle it.
10177 if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10178 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10179
10180 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10181 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(),
10182 getLangOpts());
10183
10184 llvm::SmallString<40> textToInsert;
10185 textToInsert += ' ';
10186 textToInsert += D.getIdentifier()->getName();
10187 Diag(tagLoc, diag::note_typedef_changes_linkage)
10188 << FixItHint::CreateInsertion(tagLoc, textToInsert);
10189 break;
10190 }
10191
John McCall04fcd0d2011-02-01 08:20:08 +000010192 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010193 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010194 break;
10195 }
10196
10197 default:
10198 break;
10199 }
10200
Steve Narofff93b6722007-08-28 20:14:24 +000010201 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010202}
10203
Douglas Gregord9034f02009-05-14 16:41:31 +000010204
Richard Smith4b38ded2012-03-14 23:13:10 +000010205/// \brief Check that this is a valid underlying type for an enum declaration.
10206bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10207 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10208 QualType T = TI->getType();
10209
Eli Friedman52f32b92012-12-18 02:37:32 +000010210 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010211 return false;
10212
Eli Friedman52f32b92012-12-18 02:37:32 +000010213 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10214 if (BT->isInteger())
10215 return false;
10216
Richard Smith4b38ded2012-03-14 23:13:10 +000010217 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10218 return true;
10219}
10220
10221/// Check whether this is a valid redeclaration of a previous enumeration.
10222/// \return true if the redeclaration was invalid.
10223bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10224 QualType EnumUnderlyingTy,
10225 const EnumDecl *Prev) {
10226 bool IsFixed = !EnumUnderlyingTy.isNull();
10227
10228 if (IsScoped != Prev->isScoped()) {
10229 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10230 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010231 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010232 return true;
10233 }
10234
10235 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010236 if (!EnumUnderlyingTy->isDependentType() &&
10237 !Prev->getIntegerType()->isDependentType() &&
10238 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010239 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010240 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010241 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10242 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010243 Diag(Prev->getLocation(), diag::note_previous_declaration)
10244 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010245 return true;
10246 }
10247 } else if (IsFixed != Prev->isFixed()) {
10248 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10249 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010250 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010251 return true;
10252 }
10253
10254 return false;
10255}
10256
Joao Matosdc86f942012-08-31 18:45:21 +000010257/// \brief Get diagnostic %select index for tag kind for
10258/// redeclaration diagnostic message.
10259/// WARNING: Indexes apply to particular diagnostics only!
10260///
10261/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010262static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010263 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010264 case TTK_Struct: return 0;
10265 case TTK_Interface: return 1;
10266 case TTK_Class: return 2;
10267 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010268 }
Joao Matosdc86f942012-08-31 18:45:21 +000010269}
10270
10271/// \brief Determine if tag kind is a class-key compatible with
10272/// class for redeclaration (class, struct, or __interface).
10273///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010274/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010275static bool isClassCompatTagKind(TagTypeKind Tag)
10276{
10277 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10278}
10279
Douglas Gregord9034f02009-05-14 16:41:31 +000010280/// \brief Determine whether a tag with a given kind is acceptable
10281/// as a redeclaration of the given tag declaration.
10282///
10283/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010284bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010285 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010286 SourceLocation NewTagLoc,
10287 const IdentifierInfo &Name) {
10288 // C++ [dcl.type.elab]p3:
10289 // The class-key or enum keyword present in the
10290 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010291 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010292 // refers. This rule also applies to the form of
10293 // elaborated-type-specifier that declares a class-name or
10294 // friend class since it can be construed as referring to the
10295 // definition of the class. Thus, in any
10296 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010297 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010298 // used to refer to a union (clause 9), and either the class or
10299 // struct class-key shall be used to refer to a class (clause 9)
10300 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010301 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010302 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010303 if (OldTag == NewTag)
10304 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010305
Joao Matosdc86f942012-08-31 18:45:21 +000010306 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010307 // Warn about the struct/class tag mismatch.
10308 bool isTemplate = false;
10309 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10310 isTemplate = Record->getDescribedClassTemplate();
10311
Richard Trieucaa33d32011-06-10 03:11:26 +000010312 if (!ActiveTemplateInstantiations.empty()) {
10313 // In a template instantiation, do not offer fix-its for tag mismatches
10314 // since they usually mess up the template instead of fixing the problem.
10315 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010316 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10317 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010318 return true;
10319 }
10320
10321 if (isDefinition) {
10322 // On definitions, check previous tags and issue a fix-it for each
10323 // one that doesn't match the current tag.
10324 if (Previous->getDefinition()) {
10325 // Don't suggest fix-its for redefinitions.
10326 return true;
10327 }
10328
10329 bool previousMismatch = false;
Aaron Ballman86c93902014-03-06 23:45:36 +000010330 for (auto I : Previous->redecls()) {
Richard Trieucaa33d32011-06-10 03:11:26 +000010331 if (I->getTagKind() != NewTag) {
10332 if (!previousMismatch) {
10333 previousMismatch = true;
10334 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010335 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10336 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010337 }
10338 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010339 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010340 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010341 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010342 }
10343 }
10344 return true;
10345 }
10346
10347 // Check for a previous definition. If current tag and definition
10348 // are same type, do nothing. If no definition, but disagree with
10349 // with previous tag type, give a warning, but no fix-it.
10350 const TagDecl *Redecl = Previous->getDefinition() ?
10351 Previous->getDefinition() : Previous;
10352 if (Redecl->getTagKind() == NewTag) {
10353 return true;
10354 }
10355
Douglas Gregord9034f02009-05-14 16:41:31 +000010356 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010357 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10358 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010359 Diag(Redecl->getLocation(), diag::note_previous_use);
10360
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010361 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010362 if (Previous->getDefinition()) {
10363 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010364 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010365 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010366 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010367 }
10368
Douglas Gregord9034f02009-05-14 16:41:31 +000010369 return true;
10370 }
10371 return false;
10372}
10373
Steve Naroff30d242c2007-09-15 18:49:24 +000010374/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010375/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010376/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010377/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000010378///
10379/// IsTypeSpecifier is true if this is a type-specifier (or
10380/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000010381Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010382 SourceLocation KWLoc, CXXScopeSpec &SS,
10383 IdentifierInfo *Name, SourceLocation NameLoc,
10384 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010385 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010386 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010387 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010388 SourceLocation ScopedEnumKWLoc,
10389 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000010390 TypeResult UnderlyingType,
10391 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010392 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010393 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010394 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010395 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010396 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010397
Douglas Gregord6ab8742009-05-28 23:31:59 +000010398 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010399 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010400 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010401
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010402 // FIXME: Check explicit specializations more carefully.
10403 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010404 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010405
10406 // We only need to do this matching if we have template parameters
10407 // or a scope specifier, which also conveniently avoids this work
10408 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010409 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010410 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010411 if (TemplateParameterList *TemplateParams =
10412 MatchTemplateParametersToScopeSpecifier(
10413 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10414 isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010415 if (Kind == TTK_Enum) {
10416 Diag(KWLoc, diag::err_enum_template);
10417 return 0;
10418 }
10419
Douglas Gregor3dad8422009-09-26 06:47:28 +000010420 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010421 // This is a declaration or definition of a class template (which may
10422 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010423
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010424 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010425 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010426
Douglas Gregore93e46c2009-07-22 23:48:44 +000010427 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010428 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010429 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010430 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010431 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010432 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010433 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010434 return Result.get();
10435 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010436 // The "template<>" header is extraneous.
10437 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010438 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010439 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010440 }
Mike Stump11289f42009-09-09 15:08:12 +000010441 }
10442 }
10443
Douglas Gregor0bf31402010-10-08 23:50:27 +000010444 // Figure out the underlying type if this a enum declaration. We need to do
10445 // this early, because it's needed to detect if this is an incompatible
10446 // redeclaration.
10447 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10448
10449 if (Kind == TTK_Enum) {
10450 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10451 // No underlying type explicitly specified, or we failed to parse the
10452 // type, default to int.
10453 EnumUnderlying = Context.IntTy.getTypePtr();
10454 else if (UnderlyingType.get()) {
10455 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10456 // integral type; any cv-qualification is ignored.
10457 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010458 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010459 EnumUnderlying = TI;
10460
Richard Smith4b38ded2012-03-14 23:13:10 +000010461 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010462 // Recover by falling back to int.
10463 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010464
Richard Smith4b38ded2012-03-14 23:13:10 +000010465 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010466 UPPC_FixedUnderlyingType))
10467 EnumUnderlying = Context.IntTy.getTypePtr();
10468
Alp Tokerbfa39342014-01-14 12:51:41 +000010469 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000010470 // Microsoft enums are always of int type.
10471 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010472 }
10473
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010474 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010475 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010476 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010477
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010478 RedeclarationKind Redecl = ForRedeclaration;
10479 if (TUK == TUK_Friend || TUK == TUK_Reference)
10480 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010481
10482 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010483 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010484 if (Name && SS.isNotEmpty()) {
10485 // We have a nested-name tag ('struct foo::bar').
10486
10487 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010488 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010489 Name = 0;
10490 goto CreateNewDecl;
10491 }
10492
John McCall7f41d982009-09-11 04:59:25 +000010493 // If this is a friend or a reference to a class in a dependent
10494 // context, don't try to make a decl for it.
10495 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10496 DC = computeDeclContext(SS, false);
10497 if (!DC) {
10498 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010499 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010500 }
John McCall0b66eb32010-05-01 00:40:08 +000010501 } else {
10502 DC = computeDeclContext(SS, true);
10503 if (!DC) {
10504 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10505 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010506 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010507 }
John McCall7f41d982009-09-11 04:59:25 +000010508 }
10509
John McCall0b66eb32010-05-01 00:40:08 +000010510 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010511 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010512
Douglas Gregor8761da52009-02-03 00:34:39 +000010513 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010514 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010515 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010516
John McCall1f82f242009-11-18 22:49:29 +000010517 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010518 return 0;
John McCall6538c932009-10-10 05:48:19 +000010519
John McCall1f82f242009-11-18 22:49:29 +000010520 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010521 // Name lookup did not find anything. However, if the
10522 // nested-name-specifier refers to the current instantiation,
10523 // and that current instantiation has any dependent base
10524 // classes, we might find something at instantiation time: treat
10525 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010526 // But this only makes any sense for reference-like lookups.
10527 if (Previous.wasNotFoundInCurrentInstantiation() &&
10528 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010529 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010530 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010531 }
10532
10533 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010534 Diag(NameLoc, diag::err_not_tag_in_scope)
10535 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010536 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010537 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010538 goto CreateNewDecl;
10539 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010540 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010541 // If this is a named struct, check to see if there was a previous forward
10542 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010543 // FIXME: We're looking into outer scopes here, even when we
10544 // shouldn't be. Doing so can result in ambiguities that we
10545 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010546 LookupName(Previous, S);
10547
John McCall3c581bf2013-03-20 01:53:00 +000010548 // When declaring or defining a tag, ignore ambiguities introduced
10549 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010550 if (Previous.isAmbiguous() &&
10551 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010552 LookupResult::Filter F = Previous.makeFilter();
10553 while (F.hasNext()) {
10554 NamedDecl *ND = F.next();
10555 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10556 F.erase();
10557 }
10558 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010559 }
John McCall3c581bf2013-03-20 01:53:00 +000010560
10561 // C++11 [namespace.memdef]p3:
10562 // If the name in a friend declaration is neither qualified nor
10563 // a template-id and the declaration is a function or an
10564 // elaborated-type-specifier, the lookup to determine whether
10565 // the entity has been previously declared shall not consider
10566 // any scopes outside the innermost enclosing namespace.
10567 //
10568 // Does it matter that this should be by scope instead of by
10569 // semantic context?
10570 if (!Previous.empty() && TUK == TUK_Friend) {
10571 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10572 LookupResult::Filter F = Previous.makeFilter();
10573 while (F.hasNext()) {
10574 NamedDecl *ND = F.next();
10575 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010576 if (DC->isFileContext() &&
10577 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010578 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010579 FriendSawTagOutsideEnclosingNamespace = true;
10580 }
John McCall3c581bf2013-03-20 01:53:00 +000010581 }
10582 F.done();
10583 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010584
John McCall1f82f242009-11-18 22:49:29 +000010585 // Note: there used to be some attempt at recovery here.
10586 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010587 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010588
David Blaikiebbafb8a2012-03-11 07:00:24 +000010589 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010590 // FIXME: This makes sure that we ignore the contexts associated
10591 // with C structs, unions, and enums when looking for a matching
10592 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010593 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010594 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10595 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010596 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010597 } else if (S->isFunctionPrototypeScope()) {
10598 // If this is an enum declaration in function prototype scope, set its
10599 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010600 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010601 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010602 }
10603
John McCall1f82f242009-11-18 22:49:29 +000010604 if (Previous.isSingleResult() &&
10605 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010606 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010607 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010608 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010609 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010610 }
10611
David Blaikiebbafb8a2012-03-11 07:00:24 +000010612 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010613 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010614 // This is a declaration of or a reference to "std::bad_alloc".
10615 isStdBadAlloc = true;
10616
John McCall1f82f242009-11-18 22:49:29 +000010617 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010618 // std::bad_alloc has been implicitly declared (but made invisible to
10619 // name lookup). Fill in this implicit declaration as the previous
10620 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010621 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010622 }
10623 }
John McCall1f82f242009-11-18 22:49:29 +000010624
John McCalle9eaf8e2010-03-25 21:28:06 +000010625 // If we didn't find a previous declaration, and this is a reference
10626 // (or friend reference), move to the correct scope. In C++, we
10627 // also need to do a redeclaration lookup there, just in case
10628 // there's a shadow friend decl.
10629 if (Name && Previous.empty() &&
10630 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10631 if (Invalid) goto CreateNewDecl;
10632 assert(SS.isEmpty());
10633
10634 if (TUK == TUK_Reference) {
10635 // C++ [basic.scope.pdecl]p5:
10636 // -- for an elaborated-type-specifier of the form
10637 //
10638 // class-key identifier
10639 //
10640 // if the elaborated-type-specifier is used in the
10641 // decl-specifier-seq or parameter-declaration-clause of a
10642 // function defined in namespace scope, the identifier is
10643 // declared as a class-name in the namespace that contains
10644 // the declaration; otherwise, except as a friend
10645 // declaration, the identifier is declared in the smallest
10646 // non-class, non-function-prototype scope that contains the
10647 // declaration.
10648 //
10649 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10650 // C structs and unions.
10651 //
10652 // It is an error in C++ to declare (rather than define) an enum
10653 // type, including via an elaborated type specifier. We'll
10654 // diagnose that later; for now, declare the enum in the same
10655 // scope as we would have picked for any other tag type.
10656 //
10657 // GNU C also supports this behavior as part of its incomplete
10658 // enum types extension, while GNU C++ does not.
10659 //
10660 // Find the context where we'll be declaring the tag.
10661 // FIXME: We would like to maintain the current DeclContext as the
10662 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010663 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010664 SearchDC = SearchDC->getParent();
10665
10666 // Find the scope where we'll be declaring the tag.
10667 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010668 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010669 S->isFunctionPrototypeScope()) ||
10670 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010671 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010672 S = S->getParent();
10673 } else {
10674 assert(TUK == TUK_Friend);
10675 // C++ [namespace.memdef]p3:
10676 // If a friend declaration in a non-local class first declares a
10677 // class or function, the friend class or function is a member of
10678 // the innermost enclosing namespace.
10679 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010680 }
10681
John McCalle87beb22010-04-23 18:46:30 +000010682 // In C++, we need to do a redeclaration lookup to properly
10683 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010684 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010685 Previous.setRedeclarationKind(ForRedeclaration);
10686 LookupQualifiedName(Previous, SearchDC);
10687 }
10688 }
10689
John McCall1f82f242009-11-18 22:49:29 +000010690 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000010691 NamedDecl *PrevDecl = Previous.getFoundDecl();
10692 NamedDecl *DirectPrevDecl =
10693 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000010694
10695 // It's okay to have a tag decl in the same scope as a typedef
10696 // which hides a tag decl in the same scope. Finding this
10697 // insanity with a redeclaration lookup can only actually happen
10698 // in C++.
10699 //
10700 // This is also okay for elaborated-type-specifiers, which is
10701 // technically forbidden by the current standard but which is
10702 // okay according to the likely resolution of an open issue;
10703 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010704 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010705 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010706 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10707 TagDecl *Tag = TT->getDecl();
10708 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010709 Tag->getDeclContext()->getRedeclContext()
10710 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010711 PrevDecl = Tag;
10712 Previous.clear();
10713 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010714 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010715 }
10716 }
10717 }
10718 }
10719
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010720 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010721 // If this is a use of a previous tag, or if the tag is already declared
10722 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010723 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010724 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000010725 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000010726 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010727 // Make sure that this wasn't declared as an enum and now used as a
10728 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010729 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10730 TUK == TUK_Definition, KWLoc,
10731 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010732 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010733 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10734 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010735 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010736 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010737 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010738 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10739 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010740 else
10741 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010742 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010743
Mike Stump11289f42009-09-09 15:08:12 +000010744 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010745 Kind = PrevTagDecl->getTagKind();
10746 else {
10747 // Recover by making this an anonymous redefinition.
10748 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010749 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010750 Invalid = true;
10751 }
10752 }
10753
Douglas Gregor0bf31402010-10-08 23:50:27 +000010754 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10755 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10756
Richard Smith0f8ee222012-01-10 01:33:14 +000010757 // If this is an elaborated-type-specifier for a scoped enumeration,
10758 // the 'class' keyword is not necessary and not permitted.
10759 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10760 if (ScopedEnum)
10761 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10762 << PrevEnum->isScoped()
10763 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10764 return PrevTagDecl;
10765 }
10766
Richard Smith4b38ded2012-03-14 23:13:10 +000010767 QualType EnumUnderlyingTy;
10768 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000010769 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000010770 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10771 EnumUnderlyingTy = QualType(T, 0);
10772
Douglas Gregor0bf31402010-10-08 23:50:27 +000010773 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010774 // returning the previous declaration, unless this is a definition,
10775 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010776 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10777 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010778 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010779 }
10780
David Majnemer55890bf2013-06-11 03:51:23 +000010781 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010782 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010783 // except that a nested class or member class template can be declared
10784 // and then later defined.
10785 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10786 S->isDeclScope(PrevDecl)) {
10787 Diag(NameLoc, diag::ext_member_redeclared);
10788 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10789 }
10790
Douglas Gregor170512f2009-04-01 23:51:29 +000010791 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010792 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010793
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010794 // FIXME: In the future, return a variant or some other clue
10795 // for the consumer of this Decl to know it doesn't own it.
10796 // For our current ASTs this shouldn't be a problem, but will
10797 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010798 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010799 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010800 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010801
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010802 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010803 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010804 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010805 // If we're defining a specialization and the previous definition
10806 // is from an implicit instantiation, don't emit an error
10807 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010808 bool IsExplicitSpecializationAfterInstantiation = false;
10809 if (isExplicitSpecialization) {
10810 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10811 IsExplicitSpecializationAfterInstantiation =
10812 RD->getTemplateSpecializationKind() !=
10813 TSK_ExplicitSpecialization;
10814 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10815 IsExplicitSpecializationAfterInstantiation =
10816 ED->getTemplateSpecializationKind() !=
10817 TSK_ExplicitSpecialization;
10818 }
10819
10820 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010821 // A redeclaration in function prototype scope in C isn't
10822 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010823 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010824 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10825 else
10826 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010827 Diag(Def->getLocation(), diag::note_previous_definition);
10828 // If this is a redefinition, recover by making this
10829 // struct be anonymous, which will make any later
10830 // references get the previous definition.
10831 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010832 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010833 Invalid = true;
10834 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010835 } else {
10836 // If the type is currently being defined, complain
10837 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010838 const TagType *Tag
10839 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010840 if (Tag->isBeingDefined()) {
10841 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010842 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010843 diag::note_previous_definition);
10844 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010845 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010846 Invalid = true;
10847 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010848 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010849
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010850 // Okay, this is definition of a previously declared or referenced
10851 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010852 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010853 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010854 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000010855 // have a definition. Just create a new decl.
10856
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010857 } else {
10858 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000010859 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010860 // new decl/type. We set PrevDecl to NULL so that the entities
10861 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000010862 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000010863 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010864 // If we get here, we're going to create a new Decl. If PrevDecl
10865 // is non-NULL, it's a definition of the tag declared by
10866 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000010867
10868
10869 // Otherwise, PrevDecl is not a tag, but was found with tag
10870 // lookup. This is only actually possible in C++, where a few
10871 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010872 } else {
John McCalle87beb22010-04-23 18:46:30 +000010873 // Use a better diagnostic if an elaborated-type-specifier
10874 // found the wrong kind of type on the first
10875 // (non-redeclaration) lookup.
10876 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10877 !Previous.isForRedeclaration()) {
10878 unsigned Kind = 0;
10879 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010880 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10881 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010882 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10883 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10884 Invalid = true;
10885
10886 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000010887 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10888 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000010889 // do nothing
10890
10891 // Diagnose implicit declarations introduced by elaborated types.
10892 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10893 unsigned Kind = 0;
10894 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010895 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10896 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010897 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10898 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10899 Invalid = true;
10900
10901 // Otherwise it's a declaration. Call out a particularly common
10902 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000010903 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10904 unsigned Kind = 0;
10905 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000010906 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000010907 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000010908 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10909 Invalid = true;
10910
10911 // Otherwise, diagnose.
10912 } else {
10913 // The tag name clashes with something else in the target scope,
10914 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010915 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000010916 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010917 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000010918 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010919 }
John McCalle87beb22010-04-23 18:46:30 +000010920
10921 // The existing declaration isn't relevant to us; we're in a
10922 // new scope, so clear out the previous declaration.
10923 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000010924 }
Chris Lattner18b19622007-01-22 07:39:13 +000010925 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000010926
Chris Lattner438e5012008-12-17 07:13:27 +000010927CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000010928
John McCall1f82f242009-11-18 22:49:29 +000010929 TagDecl *PrevDecl = 0;
10930 if (Previous.isSingleResult())
10931 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10932
Chris Lattnerbf0b7982007-01-23 04:27:41 +000010933 // If there is an identifier, use the location of the identifier as the
10934 // location of the decl, otherwise use the location of the struct/union
10935 // keyword.
10936 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000010937
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010938 // Otherwise, create a new declaration. If there is a previous
10939 // declaration of the same entity, the two will be linked via
10940 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000010941 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000010942
Douglas Gregor0bf31402010-10-08 23:50:27 +000010943 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010944 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000010945 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10946 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010947 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010948 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010949 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000010950 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010951 if (TUK != TUK_Definition && !Invalid) {
10952 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000010953 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10954 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010955 // C++0x: 7.2p2: opaque-enum-declaration.
10956 // Conflicts are diagnosed above. Do nothing.
10957 }
10958 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010959 Diag(Loc, diag::ext_forward_ref_enum_def)
10960 << New;
10961 Diag(Def->getLocation(), diag::note_previous_definition);
10962 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000010963 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000010964 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000010965 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010966 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000010967 DiagID = diag::err_forward_ref_enum;
10968 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010969
10970 // If this is a forward-declared reference to an enumeration, make a
10971 // note of it; we won't actually be introducing the declaration into
10972 // the declaration context.
10973 if (TUK == TUK_Reference)
10974 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010975 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000010976 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000010977
10978 if (EnumUnderlying) {
10979 EnumDecl *ED = cast<EnumDecl>(New);
10980 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10981 ED->setIntegerTypeSourceInfo(TI);
10982 else
10983 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10984 ED->setPromotionType(ED->getIntegerType());
10985 }
10986
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000010987 } else {
10988 // struct/union/class
10989
Chris Lattner776fac82007-06-09 00:53:06 +000010990 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10991 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010992 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000010993 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010994 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010995 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010996
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010997 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000010998 StdBadAlloc = cast<CXXRecordDecl>(New);
10999 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011000 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011001 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000011002 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011003
Richard Smith649c7b062014-01-08 00:56:48 +000011004 // C++11 [dcl.type]p3:
11005 // A type-specifier-seq shall not define a class or enumeration [...].
11006 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11007 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11008 << Context.getTagDeclType(New);
11009 Invalid = true;
11010 }
11011
John McCall3e11ebe2010-03-15 10:12:16 +000011012 // Maybe add qualifier info.
11013 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011014 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011015 // If this is either a declaration or a definition, check the
11016 // nested-name-specifier against the current context. We don't do this
11017 // for explicit specializations, because they have similar checking
11018 // (with more specific diagnostics) in the call to
11019 // CheckMemberSpecialization, below.
11020 if (!isExplicitSpecialization &&
11021 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11022 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11023 Invalid = true;
11024
Douglas Gregor14454802011-02-25 02:25:35 +000011025 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000011026 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000011027 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000011028 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011029 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000011030 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011031 }
11032 else
11033 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011034 }
11035
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011036 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11037 // Add alignment attributes if necessary; these attributes are checked when
11038 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011039 //
11040 // It is important for implementing the correct semantics that this
11041 // happen here (in act on tag decl). The #pragma pack stack is
11042 // maintained as a result of parser callbacks which can occur at
11043 // many points during the parsing of a struct declaration (because
11044 // the #pragma tokens are effectively skipped over during the
11045 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011046 if (TUK == TUK_Definition) {
11047 AddAlignmentAttributesForRecord(RD);
11048 AddMsStructLayoutForRecord(RD);
11049 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011050 }
11051
Douglas Gregor21823bf2011-12-20 18:11:52 +000011052 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011053 if (isExplicitSpecialization)
11054 Diag(New->getLocation(), diag::err_module_private_specialization)
11055 << 2
11056 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011057 // __module_private__ does not apply to local classes. However, we only
11058 // diagnose this as an error when the declaration specifiers are
11059 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011060 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011061 New->setModulePrivate();
11062 }
11063
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011064 // If this is a specialization of a member class (of a class template),
11065 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011066 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011067 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011068
Douglas Gregordee1be82009-01-17 00:42:38 +000011069 if (Invalid)
11070 New->setInvalidDecl();
11071
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011072 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011073 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011074
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011075 // If we're declaring or defining a tag in function prototype scope in C,
11076 // note that this type can only be used within the function and add it to
11077 // the list of decls to inject into the function definition scope.
11078 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
11079 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
Douglas Gregor658b9552009-01-09 22:42:13 +000011080 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011081 DeclsInPrototypeScope.push_back(New);
11082 }
Douglas Gregor658b9552009-01-09 22:42:13 +000011083
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011084 // Set the lexical context. If the tag has a C++ scope specifier, the
11085 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011086 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011087
John McCallaa74a0c2009-08-28 07:59:38 +000011088 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011089 // In Microsoft mode, a friend declaration also acts as a forward
11090 // declaration so we always pass true to setObjectOfFriendDecl to make
11091 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011092 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011093 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11094 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011095
Anders Carlsson5558ca12009-03-26 01:19:02 +000011096 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011097 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011098 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011099
John McCall9bb74a52009-07-31 02:45:11 +000011100 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011101 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011102
Chris Lattner18b19622007-01-22 07:39:13 +000011103 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011104 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011105 // We might be replacing an existing declaration in the lookup tables;
11106 // if so, borrow its access specifier.
11107 if (PrevDecl)
11108 New->setAccess(PrevDecl->getAccess());
11109
Sebastian Redl50c68252010-08-31 00:36:30 +000011110 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011111 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011112 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011113 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11114 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011115 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011116 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011117 PushOnScopeChains(New, S, !IsForwardReference);
11118 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011119 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011120
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011121 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011122 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011123 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011124
Douglas Gregor27821ce2009-07-07 16:35:42 +000011125 // If this is the C FILE type, notify the AST context.
11126 if (IdentifierInfo *II = New->getIdentifier())
11127 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011128 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011129 II->isStr("FILE"))
11130 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011131
Rafael Espindolac67f2232012-05-10 02:50:16 +000011132 if (PrevDecl)
11133 mergeDeclAttributes(New, PrevDecl);
11134
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011135 // If there's a #pragma GCC visibility in scope, set the visibility of this
11136 // record.
11137 AddPushedVisibilityAttribute(New);
11138
Douglas Gregord6ab8742009-05-28 23:31:59 +000011139 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011140 // In C++, don't return an invalid declaration. We can't recover well from
11141 // the cases where we make the type anonymous.
11142 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011143}
Chris Lattner1300fb92007-01-23 23:42:53 +000011144
John McCall48871652010-08-21 09:40:31 +000011145void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011146 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011147 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011148
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011149 // Enter the tag context.
11150 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011151
11152 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011153
11154 // If there's a #pragma GCC visibility in scope, set the visibility of this
11155 // record.
11156 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011157}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011158
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011159Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011160 assert(isa<ObjCContainerDecl>(IDecl) &&
11161 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11162 DeclContext *OCD = cast<DeclContext>(IDecl);
11163 assert(getContainingDC(OCD) == CurContext &&
11164 "The next DeclContext should be lexically contained in the current one.");
11165 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011166 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011167}
11168
John McCall48871652010-08-21 09:40:31 +000011169void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011170 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011171 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011172 SourceLocation LBraceLoc) {
11173 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011174 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011175
John McCall1c7e6ec2009-12-20 07:58:13 +000011176 FieldCollector->StartClass();
11177
11178 if (!Record->getIdentifier())
11179 return;
11180
Anders Carlsson30f29442011-03-25 14:31:08 +000011181 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011182 Record->addAttr(new (Context)
11183 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11184
John McCall1c7e6ec2009-12-20 07:58:13 +000011185 // C++ [class]p2:
11186 // [...] The class-name is also inserted into the scope of the
11187 // class itself; this is known as the injected-class-name. For
11188 // purposes of access checking, the injected-class-name is treated
11189 // as if it were a public member name.
11190 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011191 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11192 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011193 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011194 /*PrevDecl=*/0,
11195 /*DelayTypeCreation=*/true);
11196 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011197 InjectedClassName->setImplicit();
11198 InjectedClassName->setAccess(AS_public);
11199 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11200 InjectedClassName->setDescribedClassTemplate(Template);
11201 PushOnScopeChains(InjectedClassName, S);
11202 assert(InjectedClassName->isInjectedClassName() &&
11203 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011204}
11205
John McCall48871652010-08-21 09:40:31 +000011206void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011207 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011208 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011209 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011210 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011211
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011212 // Make sure we "complete" the definition even it is invalid.
11213 if (Tag->isBeingDefined()) {
11214 assert(Tag->isInvalidDecl() && "We should already have completed it");
11215 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11216 RD->completeDefinition();
11217 }
11218
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011219 if (isa<CXXRecordDecl>(Tag))
11220 FieldCollector->FinishClass();
11221
11222 // Exit this scope of this tag's definition.
11223 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011224
11225 if (getCurLexicalContext()->isObjCContainer() &&
11226 Tag->getDeclContext()->isFileContext())
11227 Tag->setTopLevelDeclInObjCContainer();
11228
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011229 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011230 if (!Tag->isInvalidDecl())
11231 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011232}
Chris Lattner535b8302008-06-21 19:39:06 +000011233
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011234void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011235 // Exit this scope of this interface definition.
11236 PopDeclContext();
11237}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011238
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011239void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011240 assert(DC == CurContext && "Mismatch of container contexts");
11241 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011242 ActOnObjCContainerFinishDefinition();
11243}
11244
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011245void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11246 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011247 OriginalLexicalContext = 0;
11248}
11249
John McCall48871652010-08-21 09:40:31 +000011250void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011251 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011252 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011253 Tag->setInvalidDecl();
11254
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011255 // Make sure we "complete" the definition even it is invalid.
11256 if (Tag->isBeingDefined()) {
11257 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11258 RD->completeDefinition();
11259 }
11260
John McCall71ba5f22010-03-17 19:25:57 +000011261 // We're undoing ActOnTagStartDefinition here, not
11262 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11263 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011264
11265 PopDeclContext();
11266}
11267
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011268// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011269ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11270 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011271 QualType FieldTy, bool IsMsStruct,
11272 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011273 // Default to true; that shouldn't confuse checks for emptiness
11274 if (ZeroWidth)
11275 *ZeroWidth = true;
11276
Chris Lattner73bf7b42009-03-05 22:45:59 +000011277 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011278 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011279 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011280 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011281 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011282 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011283 if (FieldName)
11284 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11285 << FieldName << FieldTy << BitWidth->getSourceRange();
11286 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11287 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011288 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11289 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011290 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011291
11292 // If the bit-width is type- or value-dependent, don't try to check
11293 // it now.
11294 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011295 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011296
Anders Carlsson5df391e2008-12-06 20:33:04 +000011297 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011298 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11299 if (ICE.isInvalid())
11300 return ICE;
11301 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011302
Eli Friedmanc96d4962009-08-15 21:55:26 +000011303 if (Value != 0 && ZeroWidth)
11304 *ZeroWidth = false;
11305
Chris Lattner81ed6802008-12-12 04:56:04 +000011306 // Zero-width bitfield is ok for anonymous field.
11307 if (Value == 0 && FieldName)
11308 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011309
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011310 if (Value.isSigned() && Value.isNegative()) {
11311 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011312 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011313 << FieldName << Value.toString(10);
11314 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11315 << Value.toString(10);
11316 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011317
Douglas Gregor1efa4372009-03-11 18:59:21 +000011318 if (!FieldTy->isDependentType()) {
11319 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011320 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011321 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11322 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011323 if (FieldName)
11324 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11325 << FieldName << (unsigned)Value.getZExtValue()
11326 << (unsigned)TypeSize;
11327
11328 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11329 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11330 }
11331
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011332 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011333 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11334 << FieldName << (unsigned)Value.getZExtValue()
11335 << (unsigned)TypeSize;
11336 else
11337 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11338 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011339 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011340 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011341
Richard Smithf4c51d92012-02-04 09:53:13 +000011342 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011343}
11344
Richard Smith938f40b2011-06-11 17:19:42 +000011345/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011346/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011347Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011348 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011349 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011350 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011351 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011352 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011353}
11354
11355/// HandleField - Analyze a field of a C struct or a C++ data member.
11356///
11357FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11358 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011359 Declarator &D, Expr *BitWidth,
11360 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011361 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011362 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011363 SourceLocation Loc = DeclStart;
11364 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011365
John McCall8cb7bdf2010-06-04 23:28:52 +000011366 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11367 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011368 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011369 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011370
Douglas Gregora02a72a2010-12-15 23:18:36 +000011371 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11372 UPPC_DataMemberType)) {
11373 D.setInvalidType();
11374 T = Context.IntTy;
11375 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11376 }
11377 }
11378
Matt Arsenault376f7202013-02-26 21:16:00 +000011379 // TR 18037 does not allow fields to be declared with address spaces.
11380 if (T.getQualifiers().hasAddressSpace()) {
11381 Diag(Loc, diag::err_field_with_address_space);
11382 D.setInvalidType();
11383 }
11384
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011385 // OpenCL 1.2 spec, s6.9 r:
11386 // The event type cannot be used to declare a structure or union field.
11387 if (LangOpts.OpenCL && T->isEventT()) {
11388 Diag(Loc, diag::err_event_t_struct_field);
11389 D.setInvalidType();
11390 }
11391
Richard Smithb1402ae2013-03-18 22:52:47 +000011392 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011393
Richard Smithb4a9e862013-04-12 22:46:28 +000011394 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11395 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11396 diag::err_invalid_thread)
11397 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011398
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011399 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011400 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011401 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11402 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011403 switch (Previous.getResultKind()) {
11404 case LookupResult::Found:
11405 case LookupResult::FoundUnresolvedValue:
11406 PrevDecl = Previous.getAsSingle<NamedDecl>();
11407 break;
11408
11409 case LookupResult::FoundOverloaded:
11410 PrevDecl = Previous.getRepresentativeDecl();
11411 break;
11412
11413 case LookupResult::NotFound:
11414 case LookupResult::NotFoundInCurrentInstantiation:
11415 case LookupResult::Ambiguous:
11416 break;
11417 }
11418 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011419
11420 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11421 // Maybe we will complain about the shadowed template parameter.
11422 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11423 // Just pretend that we didn't see the previous declaration.
11424 PrevDecl = 0;
11425 }
11426
Douglas Gregor1efa4372009-03-11 18:59:21 +000011427 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11428 PrevDecl = 0;
11429
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011430 bool Mutable
11431 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011432 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011433 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011434 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011435 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011436
11437 if (NewFD->isInvalidDecl())
11438 Record->setInvalidDecl();
11439
Douglas Gregor3baa6702011-09-12 16:11:24 +000011440 if (D.getDeclSpec().isModulePrivateSpecified())
11441 NewFD->setModulePrivate();
11442
Douglas Gregor1efa4372009-03-11 18:59:21 +000011443 if (NewFD->isInvalidDecl() && PrevDecl) {
11444 // Don't introduce NewFD into scope; there's already something
11445 // with the same name in the same scope.
11446 } else if (II) {
11447 PushOnScopeChains(NewFD, S);
11448 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011449 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011450
11451 return NewFD;
11452}
11453
11454/// \brief Build a new FieldDecl and check its well-formedness.
11455///
11456/// This routine builds a new FieldDecl given the fields name, type,
11457/// record, etc. \p PrevDecl should refer to any previous declaration
11458/// with the same name and in the same scope as the field to be
11459/// created.
11460///
11461/// \returns a new FieldDecl.
11462///
Mike Stump11289f42009-09-09 15:08:12 +000011463/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011464FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011465 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011466 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011467 bool Mutable, Expr *BitWidth,
11468 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011469 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011470 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011471 Declarator *D) {
11472 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011473 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011474 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011475
Douglas Gregor1efa4372009-03-11 18:59:21 +000011476 // If we receive a broken type, recover by assuming 'int' and
11477 // marking this declaration as invalid.
11478 if (T.isNull()) {
11479 InvalidDecl = true;
11480 T = Context.IntTy;
11481 }
11482
Eli Friedmand0e8de22009-12-07 00:22:08 +000011483 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011484 if (!EltTy->isDependentType()) {
11485 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11486 // Fields of incomplete type force their record to be invalid.
11487 Record->setInvalidDecl();
11488 InvalidDecl = true;
11489 } else {
11490 NamedDecl *Def;
11491 EltTy->isIncompleteType(&Def);
11492 if (Def && Def->isInvalidDecl()) {
11493 Record->setInvalidDecl();
11494 InvalidDecl = true;
11495 }
11496 }
John McCall2677e102010-08-16 23:42:35 +000011497 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011498
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011499 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11500 if (BitWidth && getLangOpts().OpenCL) {
11501 Diag(Loc, diag::err_opencl_bitfields);
11502 InvalidDecl = true;
11503 }
11504
Steve Naroff8eeeb132007-05-08 21:09:37 +000011505 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11506 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011507 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011508 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011509 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011510
11511 TypeSourceInfo *FixedTInfo =
11512 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11513 SizeIsNegative,
11514 Oversized);
11515 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011516 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011517 TInfo = FixedTInfo;
11518 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011519 } else {
11520 if (SizeIsNegative)
11521 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011522 else if (Oversized.getBoolValue())
11523 Diag(Loc, diag::err_array_too_large)
11524 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011525 else
11526 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011527 InvalidDecl = true;
11528 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011529 }
Mike Stump11289f42009-09-09 15:08:12 +000011530
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011531 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011532 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11533 diag::err_abstract_type_in_decl,
11534 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011535 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011536
Eli Friedmanc96d4962009-08-15 21:55:26 +000011537 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011538 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011539 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011540 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11541 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011542 if (!BitWidth) {
11543 InvalidDecl = true;
11544 BitWidth = 0;
11545 ZeroWidth = false;
11546 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011547 }
Mike Stump11289f42009-09-09 15:08:12 +000011548
John McCallb1cd7da2010-06-04 08:34:12 +000011549 // Check that 'mutable' is consistent with the type of the declaration.
11550 if (!InvalidDecl && Mutable) {
11551 unsigned DiagID = 0;
11552 if (T->isReferenceType())
11553 DiagID = diag::err_mutable_reference;
11554 else if (T.isConstQualified())
11555 DiagID = diag::err_mutable_const;
11556
11557 if (DiagID) {
11558 SourceLocation ErrLoc = Loc;
11559 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11560 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11561 Diag(ErrLoc, DiagID);
11562 Mutable = false;
11563 InvalidDecl = true;
11564 }
11565 }
11566
Richard Smithab44d5b2013-12-10 08:25:00 +000011567 // C++11 [class.union]p8 (DR1460):
11568 // At most one variant member of a union may have a
11569 // brace-or-equal-initializer.
11570 if (InitStyle != ICIS_NoInit)
11571 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11572
Abramo Bagnaradff19302011-03-08 08:55:46 +000011573 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011574 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011575 if (InvalidDecl)
11576 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011577
Douglas Gregor1efa4372009-03-11 18:59:21 +000011578 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11579 Diag(Loc, diag::err_duplicate_member) << II;
11580 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11581 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011582 }
11583
David Blaikiebbafb8a2012-03-11 07:00:24 +000011584 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011585 if (Record->isUnion()) {
11586 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11587 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11588 if (RDecl->getDefinition()) {
11589 // C++ [class.union]p1: An object of a class with a non-trivial
11590 // constructor, a non-trivial copy constructor, a non-trivial
11591 // destructor, or a non-trivial copy assignment operator
11592 // cannot be a member of a union, nor can an array of such
11593 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011594 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011595 NewFD->setInvalidDecl();
11596 }
11597 }
11598
11599 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011600 // the program is ill-formed, except when compiling with MSVC extensions
11601 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011602 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011603 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11604 diag::ext_union_member_of_reference_type :
11605 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011606 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011607 if (!getLangOpts().MicrosoftExt)
11608 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011609 }
11610 }
11611 }
11612
Douglas Gregor1efa4372009-03-11 18:59:21 +000011613 // FIXME: We need to pass in the attributes given an AST
11614 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011615 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011616 // FIXME: The current scope is almost... but not entirely... correct here.
11617 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011618
Richard Smith848e1f12013-02-01 08:12:08 +000011619 if (NewFD->hasAttrs())
11620 CheckAlignasUnderalignment(NewFD);
11621 }
11622
John McCall31168b02011-06-15 23:02:42 +000011623 // In auto-retain/release, infer strong retension for fields of
11624 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011625 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011626 NewFD->setInvalidDecl();
11627
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011628 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011629 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011630
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011631 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011632 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011633}
11634
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011635bool Sema::CheckNontrivialField(FieldDecl *FD) {
11636 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011637 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011638
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011639 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11640 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011641
11642 QualType EltTy = Context.getBaseElementType(FD->getType());
11643 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011644 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011645 if (RDecl->getDefinition()) {
11646 // We check for copy constructors before constructors
11647 // because otherwise we'll never get complaints about
11648 // copy constructors.
11649
11650 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011651 // We're required to check for any non-trivial constructors. Since the
11652 // implicit default constructor is suppressed if there are any
11653 // user-declared constructors, we just need to check that there is a
11654 // trivial default constructor and a trivial copy constructor. (We don't
11655 // worry about move constructors here, since this is a C++98 check.)
11656 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011657 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011658 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011659 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011660 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011661 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011662 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011663 member = CXXDestructor;
11664
11665 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011666 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011667 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011668 // Objective-C++ ARC: it is an error to have a non-trivial field of
11669 // a union. However, system headers in Objective-C programs
11670 // occasionally have Objective-C lifetime objects within unions,
11671 // and rather than cause the program to fail, we make those
11672 // members unavailable.
11673 SourceLocation Loc = FD->getLocation();
11674 if (getSourceManager().isInSystemHeader(Loc)) {
11675 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000011676 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11677 "this system field has retaining ownership",
11678 Loc));
John McCall31168b02011-06-15 23:02:42 +000011679 return false;
11680 }
11681 }
Richard Smithf720df02011-10-19 20:41:51 +000011682
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011683 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011684 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11685 diag::err_illegal_union_or_anon_struct_member)
11686 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011687 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011688 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011689 }
11690 }
11691 }
Richard Smith92f241f2012-12-08 02:53:02 +000011692
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011693 return false;
11694}
11695
Mike Stump11289f42009-09-09 15:08:12 +000011696/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011697/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011698static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011699TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011700 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011701 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011702 case tok::objc_private: return ObjCIvarDecl::Private;
11703 case tok::objc_public: return ObjCIvarDecl::Public;
11704 case tok::objc_protected: return ObjCIvarDecl::Protected;
11705 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011706 }
11707}
11708
Mike Stump11289f42009-09-09 15:08:12 +000011709/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011710/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011711Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011712 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011713 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011714 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011715
Fariborz Jahaniande615832008-04-10 23:32:45 +000011716 IdentifierInfo *II = D.getIdentifier();
11717 Expr *BitWidth = (Expr*)BitfieldWidth;
11718 SourceLocation Loc = DeclStart;
11719 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011720
Fariborz Jahaniande615832008-04-10 23:32:45 +000011721 // FIXME: Unnamed fields can be handled in various different ways, for
11722 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011723
John McCall8cb7bdf2010-06-04 23:28:52 +000011724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11725 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011726
Fariborz Jahaniande615832008-04-10 23:32:45 +000011727 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011728 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011729 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011730 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011731 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011732 } else {
11733 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011734
Fariborz Jahaniande615832008-04-10 23:32:45 +000011735 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011736
Fariborz Jahaniande615832008-04-10 23:32:45 +000011737 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011738 if (T->isReferenceType()) {
11739 Diag(Loc, diag::err_ivar_reference_type);
11740 D.setInvalidType();
11741 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011742 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11743 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011744 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011745 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011746 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011747 }
Mike Stump11289f42009-09-09 15:08:12 +000011748
Ted Kremenek73295fa2008-07-23 18:04:17 +000011749 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011750 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011751 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11752 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011753 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011754 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011755 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11756 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011757 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011758 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011759 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011760 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011761 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011762 EnclosingContext = IMPDecl->getClassInterface();
11763 assert(EnclosingContext && "Implementation has no class interface!");
11764 }
11765 else
11766 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011767 } else {
11768 if (ObjCCategoryDecl *CDecl =
11769 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011770 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011771 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011772 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011773 }
11774 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011775 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011776 }
Mike Stump11289f42009-09-09 15:08:12 +000011777
Ted Kremenek73295fa2008-07-23 18:04:17 +000011778 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011779 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11780 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011781 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011782
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011783 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011784 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011785 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011786 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011787 && !isa<TagDecl>(PrevDecl)) {
11788 Diag(Loc, diag::err_duplicate_member) << II;
11789 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11790 NewID->setInvalidDecl();
11791 }
11792 }
11793
Ted Kremenek73295fa2008-07-23 18:04:17 +000011794 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011795 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011796
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011797 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011798 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011799
John McCall31168b02011-06-15 23:02:42 +000011800 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011801 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011802 NewID->setInvalidDecl();
11803
Douglas Gregor3baa6702011-09-12 16:11:24 +000011804 if (D.getDeclSpec().isModulePrivateSpecified())
11805 NewID->setModulePrivate();
11806
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011807 if (II) {
11808 // FIXME: When interfaces are DeclContexts, we'll need to add
11809 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011810 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011811 IdResolver.AddDecl(NewID);
11812 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011813
John McCall5fb5df92012-06-20 06:18:46 +000011814 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011815 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011816 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011817
John McCall48871652010-08-21 09:40:31 +000011818 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011819}
11820
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011821/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011822/// class and class extensions. For every class \@interface and class
11823/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011824/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011825void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011826 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011827 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011828 return;
11829
11830 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11831 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11832
Richard Smithcaf33902011-10-10 18:28:20 +000011833 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011834 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011835 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011836 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011837 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011838 if (!CD->IsClassExtension())
11839 return;
11840 }
11841 // No need to add this to end of @implementation.
11842 else
11843 return;
11844 }
11845 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011846 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11847 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011848
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011849 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011850 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011851 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011852 Context.getTrivialTypeSourceInfo(Context.CharTy,
11853 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011854 ObjCIvarDecl::Private, BW,
11855 true);
11856 AllIvarDecls.push_back(Ivar);
11857}
11858
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011859void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11860 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11861 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000011862 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000011863
Eric Christopher7457aaf2012-07-19 22:22:51 +000011864 // If this is an Objective-C @implementation or category and we have
11865 // new fields here we should reset the layout of the interface since
11866 // it will now change.
11867 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11868 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11869 switch (DC->getKind()) {
11870 default: break;
11871 case Decl::ObjCCategory:
11872 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11873 break;
11874 case Decl::ObjCImplementation:
11875 Context.
11876 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11877 break;
11878 }
11879 }
11880
Eli Friedmana7679412012-02-07 05:00:47 +000011881 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11882
11883 // Start counting up the number of named members; make sure to include
11884 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000011885 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000011886 if (Record) {
Aaron Ballman629afae2014-03-07 19:56:05 +000011887 for (const auto *I : Record->decls()) {
11888 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Eli Friedmana7679412012-02-07 05:00:47 +000011889 if (IFD->getDeclName())
11890 ++NumNamedMembers;
11891 }
11892 }
11893
11894 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011895 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000011896
John McCall31168b02011-06-15 23:02:42 +000011897 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011898 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000011899 i != end; ++i) {
11900 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000011901
Chris Lattner720a0542007-01-25 00:44:24 +000011902 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000011903 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000011904
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011905 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000011906 // Remember all fields written by the user.
11907 RecFields.push_back(FD);
11908 }
Mike Stump11289f42009-09-09 15:08:12 +000011909
Chris Lattner73bf7b42009-03-05 22:45:59 +000011910 // If the field is already invalid for some reason, don't emit more
11911 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011912 if (FD->isInvalidDecl()) {
11913 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000011914 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000011915 }
Mike Stump11289f42009-09-09 15:08:12 +000011916
Douglas Gregorac1fb652009-03-24 19:52:54 +000011917 // C99 6.7.2.1p2:
11918 // A structure or union shall not contain a member with
11919 // incomplete or function type (hence, a structure shall not
11920 // contain an instance of itself, but may contain a pointer to
11921 // an instance of itself), except that the last member of a
11922 // structure with more than one named member may have incomplete
11923 // array type; such a structure (and any union containing,
11924 // possibly recursively, a member that is such a structure)
11925 // shall not be a member of a structure or an element of an
11926 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000011927 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011928 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000011929 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011930 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000011931 FD->setInvalidDecl();
11932 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000011933 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000011934 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000011935 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000011936 ((getLangOpts().MicrosoftExt ||
11937 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000011938 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011939 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000011940 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000011941 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000011942 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000011943 unsigned DiagID = 0;
11944 if (Record->isUnion())
11945 DiagID = getLangOpts().MicrosoftExt
11946 ? diag::ext_flexible_array_union_ms
11947 : getLangOpts().CPlusPlus
11948 ? diag::ext_flexible_array_union_gnu
11949 : diag::err_flexible_array_union;
11950 else if (Fields.size() == 1)
11951 DiagID = getLangOpts().MicrosoftExt
11952 ? diag::ext_flexible_array_empty_aggregate_ms
11953 : getLangOpts().CPlusPlus
11954 ? diag::ext_flexible_array_empty_aggregate_gnu
11955 : NumNamedMembers < 1
11956 ? diag::err_flexible_array_empty_aggregate
11957 : 0;
11958
11959 if (DiagID)
11960 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11961 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000011962 // While the layout of types that contain virtual bases is not specified
11963 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11964 // virtual bases after the derived members. This would make a flexible
11965 // array member declared at the end of an object not adjacent to the end
11966 // of the type.
11967 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11968 if (RD->getNumVBases() != 0)
11969 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11970 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000011971 if (!getLangOpts().C99)
11972 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11973 << FD->getDeclName() << Record->getTagKind();
11974
Richard Smith6fa28ff2014-01-11 00:53:35 +000011975 // If the element type has a non-trivial destructor, we would not
11976 // implicitly destroy the elements, so disallow it for now.
11977 //
11978 // FIXME: GCC allows this. We should probably either implicitly delete
11979 // the destructor of the containing class, or just allow this.
11980 QualType BaseElem = Context.getBaseElementType(FD->getType());
11981 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
11982 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000011983 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011984 FD->setInvalidDecl();
11985 EnclosingDecl->setInvalidDecl();
11986 continue;
11987 }
Chris Lattner720a0542007-01-25 00:44:24 +000011988 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000011989 if (Record)
11990 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000011991 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000011992 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000011993 diag::err_field_incomplete)) {
11994 // Incomplete type
11995 FD->setInvalidDecl();
11996 EnclosingDecl->setInvalidDecl();
11997 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011998 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000011999 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12000 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000012001 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000012002 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012003 } else {
12004 // If this is a struct/class and this is not the last element, reject
12005 // it. Note that GCC supports variable sized arrays in the middle of
12006 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000012007 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012008 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000012009 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012010 else {
12011 // We support flexible arrays at the end of structs in
12012 // other structs as an extension.
12013 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12014 << FD->getDeclName();
12015 if (Record)
12016 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012017 }
Chris Lattner720a0542007-01-25 00:44:24 +000012018 }
12019 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000012020 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12021 RequireNonAbstractType(FD->getLocation(), FD->getType(),
12022 diag::err_abstract_type_in_decl,
12023 AbstractIvarType)) {
12024 // Ivars can not have abstract class types
12025 FD->setInvalidDecl();
12026 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000012027 if (Record && FDTTy->getDecl()->hasObjectMember())
12028 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000012029 if (Record && FDTTy->getDecl()->hasVolatileMember())
12030 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012031 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012032 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012033 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12034 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12035 QualType T = Context.getObjCObjectPointerType(FD->getType());
12036 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012037 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12038 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12039 // It's an error in ARC if a field has lifetime.
12040 // We don't want to report this in a system header, though,
12041 // so we just make the field unavailable.
12042 // FIXME: that's really not sufficient; we need to make the type
12043 // itself invalid to, say, initialize or copy.
12044 QualType T = FD->getType();
12045 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12046 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12047 SourceLocation loc = FD->getLocation();
12048 if (getSourceManager().isInSystemHeader(loc)) {
12049 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012050 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12051 "this system field has retaining ownership",
12052 loc));
John McCall31168b02011-06-15 23:02:42 +000012053 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012054 } else {
12055 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012056 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012057 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012058 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012059 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012060 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012061 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012062 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012063 if (FD->getType()->isObjCObjectPointerType() ||
12064 FD->getType().isObjCGCStrong())
12065 Record->setHasObjectMember(true);
12066 else if (Context.getAsArrayType(FD->getType())) {
12067 QualType BaseType = Context.getBaseElementType(FD->getType());
12068 if (BaseType->isRecordType() &&
12069 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012070 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012071 else if (BaseType->isObjCObjectPointerType() ||
12072 BaseType.isObjCGCStrong())
12073 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012074 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012075 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012076 if (Record && FD->getType().isVolatileQualified())
12077 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012078 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012079 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012080 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012081 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012082
Chris Lattner82625602007-01-24 02:26:21 +000012083 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012084 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012085 bool Completed = false;
12086 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12087 if (!CXXRecord->isInvalidDecl()) {
12088 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012089 for (CXXRecordDecl::conversion_iterator
12090 I = CXXRecord->conversion_begin(),
12091 E = CXXRecord->conversion_end(); I != E; ++I)
12092 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012093
12094 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012095 if (CXXRecord->hasUserDeclaredDestructor()) {
12096 // Adjust user-defined destructor exception spec.
12097 if (getLangOpts().CPlusPlus11)
12098 AdjustDestructorExceptionSpec(CXXRecord,
12099 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012100 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012101
Douglas Gregor8fb95122010-09-29 00:15:42 +000012102 // Add any implicitly-declared members to this class.
12103 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12104
12105 // If we have virtual base classes, we may end up finding multiple
12106 // final overriders for a given virtual function. Check for this
12107 // problem now.
12108 if (CXXRecord->getNumVBases()) {
12109 CXXFinalOverriderMap FinalOverriders;
12110 CXXRecord->getFinalOverriders(FinalOverriders);
12111
12112 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12113 MEnd = FinalOverriders.end();
12114 M != MEnd; ++M) {
12115 for (OverridingMethods::iterator SO = M->second.begin(),
12116 SOEnd = M->second.end();
12117 SO != SOEnd; ++SO) {
12118 assert(SO->second.size() > 0 &&
12119 "Virtual function without overridding functions?");
12120 if (SO->second.size() == 1)
12121 continue;
12122
12123 // C++ [class.virtual]p2:
12124 // In a derived class, if a virtual member function of a base
12125 // class subobject has more than one final overrider the
12126 // program is ill-formed.
12127 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012128 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012129 Diag(M->first->getLocation(),
12130 diag::note_overridden_virtual_function);
12131 for (OverridingMethods::overriding_iterator
12132 OM = SO->second.begin(),
12133 OMEnd = SO->second.end();
12134 OM != OMEnd; ++OM)
12135 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012136 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012137
12138 Record->setInvalidDecl();
12139 }
12140 }
12141 CXXRecord->completeDefinition(&FinalOverriders);
12142 Completed = true;
12143 }
12144 }
12145 }
12146 }
12147
12148 if (!Completed)
12149 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012150
David Majnemer2c4e00a2014-01-29 22:07:36 +000012151 if (Record->hasAttrs()) {
Richard Smith848e1f12013-02-01 08:12:08 +000012152 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012153
David Majnemer98c9ee22014-02-07 00:43:07 +000012154 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
David Majnemer2c4e00a2014-01-29 22:07:36 +000012155 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
David Majnemer4bb09802014-02-10 19:50:15 +000012156 IA->getRange(), IA->getBestCase(),
David Majnemer2c4e00a2014-01-29 22:07:36 +000012157 IA->getSemanticSpelling());
12158 }
12159
Serge Pavlov3cb80222013-11-14 02:13:03 +000012160 // Check if the structure/union declaration is a type that can have zero
12161 // size in C. For C this is a language extension, for C++ it may cause
12162 // compatibility problems.
12163 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012164 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012165 CheckForZeroSize = true;
12166 } else {
12167 // For C++ filter out types that cannot be referenced in C code.
12168 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12169 CheckForZeroSize =
12170 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12171 !CXXRecord->isDependentType() &&
12172 CXXRecord->isCLike();
12173 }
12174 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012175 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012176 bool IsEmpty = true;
12177 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012178 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012179 E = Record->field_end();
12180 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12181 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012182 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012183 if (I->getBitWidthValue(Context) > 0)
12184 ZeroSize = false;
12185 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012186 ++NonBitFields;
12187 QualType FieldType = I->getType();
12188 if (FieldType->isIncompleteType() ||
12189 !Context.getTypeSizeInChars(FieldType).isZero())
12190 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012191 }
12192 }
12193
Serge Pavlov3cb80222013-11-14 02:13:03 +000012194 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12195 // allowed in C++, but warn if its declaration is inside
12196 // extern "C" block.
12197 if (ZeroSize) {
12198 Diag(RecLoc, getLangOpts().CPlusPlus ?
12199 diag::warn_zero_size_struct_union_in_extern_c :
12200 diag::warn_zero_size_struct_union_compat)
12201 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12202 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012203
Serge Pavlov3cb80222013-11-14 02:13:03 +000012204 // Structs without named members are extension in C (C99 6.7.2.1p7),
12205 // but are accepted by GCC.
12206 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12207 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12208 diag::ext_no_named_members_in_struct_union)
12209 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012210 }
12211 }
Chris Lattner622c1932008-02-06 00:51:33 +000012212 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012213 ObjCIvarDecl **ClsFields =
12214 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012215 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012216 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012217 // Add ivar's to class's DeclContext.
12218 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12219 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012220 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012221 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012222 // Must enforce the rule that ivars in the base classes may not be
12223 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012224 if (ID->getSuperClass())
12225 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012226 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012227 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012228 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012229 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12230 // Ivar declared in @implementation never belongs to the implementation.
12231 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012232 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012233 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012234 IMPDecl->setIvarLBraceLoc(LBrac);
12235 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012236 } else if (ObjCCategoryDecl *CDecl =
12237 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012238 // case of ivars in class extension; all other cases have been
12239 // reported as errors elsewhere.
12240 // FIXME. Class extension does not have a LocEnd field.
12241 // CDecl->setLocEnd(RBrac);
12242 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012243 // Diagnose redeclaration of private ivars.
12244 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012245 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012246 if (IDecl) {
12247 if (const ObjCIvarDecl *ClsIvar =
12248 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12249 Diag(ClsFields[i]->getLocation(),
12250 diag::err_duplicate_ivar_declaration);
12251 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12252 continue;
12253 }
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012254 for (ObjCInterfaceDecl::known_extensions_iterator
12255 Ext = IDecl->known_extensions_begin(),
12256 ExtEnd = IDecl->known_extensions_end();
12257 Ext != ExtEnd; ++Ext) {
12258 if (const ObjCIvarDecl *ClsExtIvar
12259 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012260 Diag(ClsFields[i]->getLocation(),
12261 diag::err_duplicate_ivar_declaration);
12262 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12263 continue;
12264 }
12265 }
12266 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012267 ClsFields[i]->setLexicalDeclContext(CDecl);
12268 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012269 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012270 CDecl->setIvarLBraceLoc(LBrac);
12271 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012272 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012273 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012274
12275 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012276 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012277}
12278
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012279/// \brief Determine whether the given integral value is representable within
12280/// the given type T.
12281static bool isRepresentableIntegerValue(ASTContext &Context,
12282 llvm::APSInt &Value,
12283 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012284 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012285 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012286
Douglas Gregor0bf31402010-10-08 23:50:27 +000012287 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012288 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012289 --BitWidth;
12290 return Value.getActiveBits() <= BitWidth;
12291 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012292 return Value.getMinSignedBits() <= BitWidth;
12293}
12294
12295// \brief Given an integral type, return the next larger integral type
12296// (or a NULL type of no such type exists).
12297static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12298 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12299 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012300 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012301 const unsigned NumTypes = 4;
12302 QualType SignedIntegralTypes[NumTypes] = {
12303 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12304 };
12305 QualType UnsignedIntegralTypes[NumTypes] = {
12306 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12307 Context.UnsignedLongLongTy
12308 };
12309
12310 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012311 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12312 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012313 for (unsigned I = 0; I != NumTypes; ++I)
12314 if (Context.getTypeSize(Types[I]) > BitWidth)
12315 return Types[I];
12316
12317 return QualType();
12318}
12319
Douglas Gregor954f6b272009-03-17 19:05:46 +000012320EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12321 EnumConstantDecl *LastEnumConst,
12322 SourceLocation IdLoc,
12323 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012324 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012325 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012326 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012327 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012328
12329 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12330 Val = 0;
12331
Eli Friedman7c6515a2011-12-06 00:10:34 +000012332 if (Val)
12333 Val = DefaultLvalueConversion(Val).take();
12334
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012335 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012336 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012337 EltTy = Context.DependentTy;
12338 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012339 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012340 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000012341 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000012342 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12343 // constant-expression in the enumerator-definition shall be a converted
12344 // constant expression of the underlying type.
12345 EltTy = Enum->getIntegerType();
12346 ExprResult Converted =
12347 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12348 CCEK_Enumerator);
12349 if (Converted.isInvalid())
12350 Val = 0;
12351 else
12352 Val = Converted.take();
12353 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012354 !(Val = VerifyIntegerConstantExpression(Val,
12355 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012356 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012357 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012358 if (Enum->isFixed()) {
12359 EltTy = Enum->getIntegerType();
12360
Richard Smithf8379a02012-01-18 23:55:52 +000012361 // In Obj-C and Microsoft mode, require the enumeration value to be
12362 // representable in the underlying type of the enumeration. In C++11,
12363 // we perform a non-narrowing conversion as part of converted constant
12364 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012365 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000012366 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000012367 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012368 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012369 } else
12370 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012371 } else
John Wiegley01296292011-04-08 18:41:53 +000012372 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012373 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012374 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012375 // If the underlying type is not fixed, the type of each enumerator
12376 // is the type of its initializing value:
12377 // - If an initializer is specified for an enumerator, the
12378 // initializing value has the same type as the expression.
12379 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012380 } else {
12381 // C99 6.7.2.2p2:
12382 // The expression that defines the value of an enumeration constant
12383 // shall be an integer constant expression that has a value
12384 // representable as an int.
12385
12386 // Complain if the value is not representable in an int.
12387 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12388 Diag(IdLoc, diag::ext_enum_value_not_int)
12389 << EnumVal.toString(10) << Val->getSourceRange()
12390 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12391 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12392 // Force the type of the expression to 'int'.
12393 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12394 }
12395 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012396 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012397 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012398 }
12399 }
Mike Stump11289f42009-09-09 15:08:12 +000012400
Douglas Gregor954f6b272009-03-17 19:05:46 +000012401 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012402 if (Enum->isDependentType())
12403 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012404 else if (!LastEnumConst) {
12405 // C++0x [dcl.enum]p5:
12406 // If the underlying type is not fixed, the type of each enumerator
12407 // is the type of its initializing value:
12408 // - If no initializer is specified for the first enumerator, the
12409 // initializing value has an unspecified integral type.
12410 //
12411 // GCC uses 'int' for its unspecified integral type, as does
12412 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012413 if (Enum->isFixed()) {
12414 EltTy = Enum->getIntegerType();
12415 }
12416 else {
12417 EltTy = Context.IntTy;
12418 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012419 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012420 // Assign the last value + 1.
12421 EnumVal = LastEnumConst->getInitVal();
12422 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012423 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012424
12425 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012426 if (EnumVal < LastEnumConst->getInitVal()) {
12427 // C++0x [dcl.enum]p5:
12428 // If the underlying type is not fixed, the type of each enumerator
12429 // is the type of its initializing value:
12430 //
12431 // - Otherwise the type of the initializing value is the same as
12432 // the type of the initializing value of the preceding enumerator
12433 // unless the incremented value is not representable in that type,
12434 // in which case the type is an unspecified integral type
12435 // sufficient to contain the incremented value. If no such type
12436 // exists, the program is ill-formed.
12437 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012438 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012439 // There is no integral type larger enough to represent this
12440 // value. Complain, then allow the value to wrap around.
12441 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012442 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012443 ++EnumVal;
12444 if (Enum->isFixed())
12445 // When the underlying type is fixed, this is ill-formed.
12446 Diag(IdLoc, diag::err_enumerator_wrapped)
12447 << EnumVal.toString(10)
12448 << EltTy;
12449 else
Richard Smithfaf156a2014-03-05 22:54:58 +000012450 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
Douglas Gregor0bf31402010-10-08 23:50:27 +000012451 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012452 } else {
12453 EltTy = T;
12454 }
12455
12456 // Retrieve the last enumerator's value, extent that type to the
12457 // type that is supposed to be large enough to represent the incremented
12458 // value, then increment.
12459 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012460 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012461 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012462 ++EnumVal;
12463
12464 // If we're not in C++, diagnose the overflow of enumerator values,
12465 // which in C99 means that the enumerator value is not representable in
12466 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12467 // permits enumerator values that are representable in some larger
12468 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012469 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012470 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012471 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012472 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12473 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12474 Diag(IdLoc, diag::ext_enum_value_not_int)
12475 << EnumVal.toString(10) << 1;
12476 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012477 }
12478 }
Mike Stump11289f42009-09-09 15:08:12 +000012479
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012480 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012481 // Make the enumerator value match the signedness and size of the
12482 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012483 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012484 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012485 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012486
Douglas Gregor954f6b272009-03-17 19:05:46 +000012487 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012488 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012489}
12490
12491
John McCall811a0f52010-10-22 23:36:17 +000012492Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12493 SourceLocation IdLoc, IdentifierInfo *Id,
12494 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012495 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012496 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012497 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012498 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012499
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012500 // The scope passed in may not be a decl scope. Zip up the scope tree until
12501 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012502 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012503
Chris Lattner8116d1b2007-01-25 22:38:29 +000012504 // Verify that there isn't already something declared with this name in this
12505 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012506 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012507 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012508 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012509 // Maybe we will complain about the shadowed template parameter.
12510 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12511 // Just pretend that we didn't see the previous declaration.
12512 PrevDecl = 0;
12513 }
12514
12515 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012516 // When in C++, we may get a TagDecl with the same name; in this case the
12517 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012518 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012519 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012520 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012521 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012522 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012523 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012524 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012525 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012526 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012527 }
12528 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012529
Aaron Ballman24a10472012-07-19 03:12:23 +000012530 // C++ [class.mem]p15:
12531 // If T is the name of a class, then each of the following shall have a name
12532 // different from T:
12533 // - every enumerator of every member of class T that is an unscoped
12534 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012535 if (CXXRecordDecl *Record
12536 = dyn_cast<CXXRecordDecl>(
12537 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012538 if (!TheEnumDecl->isScoped() &&
12539 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012540 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12541
John McCall811a0f52010-10-22 23:36:17 +000012542 EnumConstantDecl *New =
12543 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012544
John McCall553c0792010-01-23 00:46:32 +000012545 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012546 // Process attributes.
12547 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12548
12549 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012550 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012551 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012552 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012553
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012554 ActOnDocumentableDecl(New);
12555
John McCall48871652010-08-21 09:40:31 +000012556 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012557}
12558
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012559// Returns true when the enum initial expression does not trigger the
12560// duplicate enum warning. A few common cases are exempted as follows:
12561// Element2 = Element1
12562// Element2 = Element1 + 1
12563// Element2 = Element1 - 1
12564// Where Element2 and Element1 are from the same enum.
12565static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12566 Expr *InitExpr = ECD->getInitExpr();
12567 if (!InitExpr)
12568 return true;
12569 InitExpr = InitExpr->IgnoreImpCasts();
12570
12571 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12572 if (!BO->isAdditiveOp())
12573 return true;
12574 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12575 if (!IL)
12576 return true;
12577 if (IL->getValue() != 1)
12578 return true;
12579
12580 InitExpr = BO->getLHS();
12581 }
12582
12583 // This checks if the elements are from the same enum.
12584 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12585 if (!DRE)
12586 return true;
12587
12588 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12589 if (!EnumConstant)
12590 return true;
12591
12592 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12593 Enum)
12594 return true;
12595
12596 return false;
12597}
12598
12599struct DupKey {
12600 int64_t val;
12601 bool isTombstoneOrEmptyKey;
12602 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12603 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12604};
12605
12606static DupKey GetDupKey(const llvm::APSInt& Val) {
12607 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12608 false);
12609}
12610
12611struct DenseMapInfoDupKey {
12612 static DupKey getEmptyKey() { return DupKey(0, true); }
12613 static DupKey getTombstoneKey() { return DupKey(1, true); }
12614 static unsigned getHashValue(const DupKey Key) {
12615 return (unsigned)(Key.val * 37);
12616 }
12617 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12618 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12619 LHS.val == RHS.val;
12620 }
12621};
12622
12623// Emits a warning when an element is implicitly set a value that
12624// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012625static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12626 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012627 QualType EnumType) {
12628 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12629 Enum->getLocation()) ==
12630 DiagnosticsEngine::Ignored)
12631 return;
12632 // Avoid anonymous enums
12633 if (!Enum->getIdentifier())
12634 return;
12635
12636 // Only check for small enums.
12637 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12638 return;
12639
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012640 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12641 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012642
12643 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12644 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12645 ValueToVectorMap;
12646
12647 DuplicatesVector DupVector;
12648 ValueToVectorMap EnumMap;
12649
12650 // Populate the EnumMap with all values represented by enum constants without
12651 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012652 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012653 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012654
12655 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12656 // this constant. Skip this enum since it may be ill-formed.
12657 if (!ECD) {
12658 return;
12659 }
12660
12661 if (ECD->getInitExpr())
12662 continue;
12663
12664 DupKey Key = GetDupKey(ECD->getInitVal());
12665 DeclOrVector &Entry = EnumMap[Key];
12666
12667 // First time encountering this value.
12668 if (Entry.isNull())
12669 Entry = ECD;
12670 }
12671
12672 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012673 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012674 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12675 if (!ValidDuplicateEnum(ECD, Enum))
12676 continue;
12677
12678 DupKey Key = GetDupKey(ECD->getInitVal());
12679
12680 DeclOrVector& Entry = EnumMap[Key];
12681 if (Entry.isNull())
12682 continue;
12683
12684 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12685 // Ensure constants are different.
12686 if (D == ECD)
12687 continue;
12688
12689 // Create new vector and push values onto it.
12690 ECDVector *Vec = new ECDVector();
12691 Vec->push_back(D);
12692 Vec->push_back(ECD);
12693
12694 // Update entry to point to the duplicates vector.
12695 Entry = Vec;
12696
12697 // Store the vector somewhere we can consult later for quick emission of
12698 // diagnostics.
12699 DupVector.push_back(Vec);
12700 continue;
12701 }
12702
12703 ECDVector *Vec = Entry.get<ECDVector*>();
12704 // Make sure constants are not added more than once.
12705 if (*Vec->begin() == ECD)
12706 continue;
12707
12708 Vec->push_back(ECD);
12709 }
12710
12711 // Emit diagnostics.
12712 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12713 DupVectorEnd = DupVector.end();
12714 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12715 ECDVector *Vec = *DupVectorIter;
12716 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12717
12718 // Emit warning for one enum constant.
12719 ECDVector::iterator I = Vec->begin();
12720 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12721 << (*I)->getName() << (*I)->getInitVal().toString(10)
12722 << (*I)->getSourceRange();
12723 ++I;
12724
12725 // Emit one note for each of the remaining enum constants with
12726 // the same value.
12727 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12728 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12729 << (*I)->getName() << (*I)->getInitVal().toString(10)
12730 << (*I)->getSourceRange();
12731 delete Vec;
12732 }
12733}
12734
Mike Stump6814d1c2009-05-16 07:06:02 +000012735void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012736 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012737 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012738 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012739 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012740 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012741
12742 if (Attr)
12743 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012744
Eli Friedmand0e60972009-12-11 01:34:50 +000012745 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012746 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012747 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012748 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012749 if (!ECD) continue;
12750
12751 ECD->setType(EnumType);
12752 }
12753
John McCall9aa35be2010-05-06 08:49:23 +000012754 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012755 return;
12756 }
12757
Chris Lattner67933c02007-08-28 05:10:31 +000012758 // TODO: If the result value doesn't fit in an int, it must be a long or long
12759 // long value. ISO C does not support this, but GCC does as an extension,
12760 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012761 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12762 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12763 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012764
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012765 // Verify that all the values are okay, compute the size of the values, and
12766 // reverse the list.
12767 unsigned NumNegativeBits = 0;
12768 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012769
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012770 // Keep track of whether all elements have type int.
12771 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012772
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012773 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012774 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012775 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012776 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012777
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012778 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012779
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012780 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012781 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012782 NumPositiveBits = std::max(NumPositiveBits,
12783 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012784 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012785 NumNegativeBits = std::max(NumNegativeBits,
12786 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012787
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012788 // Keep track of whether every enum element has type int (very commmon).
12789 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012790 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012791 }
Mike Stump11289f42009-09-09 15:08:12 +000012792
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012793 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012794 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012795 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012796
John McCall56774992009-12-09 09:09:27 +000012797 // C++0x N3000 [conv.prom]p3:
12798 // An rvalue of an unscoped enumeration type whose underlying
12799 // type is not fixed can be converted to an rvalue of the first
12800 // of the following types that can represent all the values of
12801 // the enumeration: int, unsigned int, long int, unsigned long
12802 // int, long long int, or unsigned long long int.
12803 // C99 6.4.4.3p2:
12804 // An identifier declared as an enumeration constant has type int.
12805 // The C99 rule is modified by a gcc extension
12806 QualType BestPromotionType;
12807
Aaron Ballman9ead1242013-12-19 02:39:40 +000012808 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012809 // -fshort-enums is the equivalent to specifying the packed attribute on all
12810 // enum definitions.
12811 if (LangOpts.ShortEnums)
12812 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012813
Douglas Gregor0bf31402010-10-08 23:50:27 +000012814 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012815 BestType = Enum->getIntegerType();
12816 if (BestType->isPromotableIntegerType())
12817 BestPromotionType = Context.getPromotedIntegerType(BestType);
12818 else
12819 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012820 // We don't need to set BestWidth, because BestType is going to be the type
12821 // of the enumerators, but we do anyway because otherwise some compilers
12822 // warn that it might be used uninitialized.
12823 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012824 }
12825 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012826 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012827 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012828 // If it's packed, check also if it fits a char or a short.
12829 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012830 BestType = Context.SignedCharTy;
12831 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012832 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012833 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012834 BestType = Context.ShortTy;
12835 BestWidth = ShortWidth;
12836 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012837 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012838 BestWidth = IntWidth;
12839 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012840 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012841
John McCall56774992009-12-09 09:09:27 +000012842 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012843 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012844 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012845 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012846
Chris Lattner3a370bf2007-08-29 17:31:48 +000012847 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Richard Smithfaf156a2014-03-05 22:54:58 +000012848 Diag(Enum->getLocation(), diag::ext_enum_too_large);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012849 BestType = Context.LongLongTy;
12850 }
12851 }
John McCall56774992009-12-09 09:09:27 +000012852 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012853 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012854 // If there is no negative value, figure out the smallest type that fits
12855 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012856 // If it's packed, check also if it fits a char or a short.
12857 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012858 BestType = Context.UnsignedCharTy;
12859 BestPromotionType = Context.IntTy;
12860 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012861 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012862 BestType = Context.UnsignedShortTy;
12863 BestPromotionType = Context.IntTy;
12864 BestWidth = ShortWidth;
12865 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012866 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012867 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000012868 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012869 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012870 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012871 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000012872 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012873 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012874 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012875 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012876 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000012877 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012878 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012879 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012880 "How could an initializer get larger than ULL?");
12881 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012882 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012883 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012884 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012885 }
12886 }
Mike Stump11289f42009-09-09 15:08:12 +000012887
Chris Lattner3a370bf2007-08-29 17:31:48 +000012888 // Loop over all of the enumerator constants, changing their types to match
12889 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012890 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000012891 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012892 if (!ECD) continue; // Already issued a diagnostic.
12893
12894 // Standard C says the enumerators have int type, but we allow, as an
12895 // extension, the enumerators to be larger than int size. If each
12896 // enumerator value fits in an int, type it as an int, otherwise type it the
12897 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12898 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000012899
12900 // Determine whether the value fits into an int.
12901 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012902
12903 // If it fits into an integer type, force it. Otherwise force it to match
12904 // the enum decl type.
12905 QualType NewTy;
12906 unsigned NewWidth;
12907 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000012908 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000012909 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012910 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000012911 NewTy = Context.IntTy;
12912 NewWidth = IntWidth;
12913 NewSign = true;
12914 } else if (ECD->getType() == BestType) {
12915 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000012916 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012917 // C++ [dcl.enum]p4: Following the closing brace of an
12918 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012919 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012920 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012921 continue;
12922 } else {
12923 NewTy = BestType;
12924 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012925 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012926 }
12927
12928 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000012929 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012930 InitVal.setIsSigned(NewSign);
12931 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000012932
Chris Lattner3a370bf2007-08-29 17:31:48 +000012933 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000012934 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000012935 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000012936 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000012937 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000012938 ECD->getInitExpr(),
12939 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000012940 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000012941 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012942 // C++ [dcl.enum]p4: Following the closing brace of an
12943 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012944 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012945 ECD->setType(EnumType);
12946 else
12947 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012948 }
Mike Stump11289f42009-09-09 15:08:12 +000012949
John McCall9aa35be2010-05-06 08:49:23 +000012950 Enum->completeDefinition(BestType, BestPromotionType,
12951 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000012952
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012953 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000012954
12955 // Now that the enum type is defined, ensure it's not been underaligned.
12956 if (Enum->hasAttrs())
12957 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012958}
Chris Lattner1300fb92007-01-23 23:42:53 +000012959
Abramo Bagnara348823a2011-03-03 14:20:18 +000012960Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12961 SourceLocation StartLoc,
12962 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000012963 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000012964
Douglas Gregor278f52e2009-05-30 00:08:05 +000012965 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000012966 AsmString, StartLoc,
12967 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012968 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000012969 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000012970}
Eli Friedman5ed51982009-06-05 02:44:36 +000012971
Richard Smith77944862014-03-02 05:58:18 +000012972static void checkModuleImportContext(Sema &S, Module *M,
12973 SourceLocation ImportLoc,
12974 DeclContext *DC) {
12975 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
12976 switch (LSD->getLanguage()) {
12977 case LinkageSpecDecl::lang_c:
12978 if (!M->IsExternC) {
12979 S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
12980 << M->getFullModuleName();
12981 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
12982 return;
12983 }
12984 break;
12985 case LinkageSpecDecl::lang_cxx:
12986 break;
12987 }
12988 DC = LSD->getParent();
12989 }
12990
12991 while (isa<LinkageSpecDecl>(DC))
12992 DC = DC->getParent();
12993 if (!isa<TranslationUnitDecl>(DC)) {
12994 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
12995 << M->getFullModuleName() << DC;
12996 S.Diag(cast<Decl>(DC)->getLocStart(),
12997 diag::note_module_import_not_at_top_level)
12998 << DC;
12999 }
13000}
13001
Douglas Gregor22d09742012-01-03 18:04:46 +000013002DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13003 SourceLocation ImportLoc,
13004 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000013005 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000013006 Module::AllVisible,
13007 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000013008 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000013009 return true;
Richard Smith77944862014-03-02 05:58:18 +000013010
13011 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13012
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013013 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000013014 Module *ModCheck = Mod;
13015 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13016 // If we've run out of module parents, just drop the remaining identifiers.
13017 // We need the length to be consistent.
13018 if (!ModCheck)
13019 break;
13020 ModCheck = ModCheck->Parent;
13021
13022 IdentifierLocs.push_back(Path[I].second);
13023 }
13024
13025 ImportDecl *Import = ImportDecl::Create(Context,
13026 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000013027 AtLoc.isValid()? AtLoc : ImportLoc,
13028 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000013029 Context.getTranslationUnitDecl()->addDecl(Import);
13030 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000013031}
13032
Richard Smithce587f52013-11-15 04:24:58 +000013033void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
Richard Smith77944862014-03-02 05:58:18 +000013034 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13035
Richard Smithce587f52013-11-15 04:24:58 +000013036 // FIXME: Should we synthesize an ImportDecl here?
13037 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13038 /*Complain=*/true);
13039}
13040
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013041void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
13042 // Create the implicit import declaration.
13043 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13044 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13045 Loc, Mod, Loc);
13046 TU->addDecl(ImportD);
13047 Consumer.HandleImplicitImportDecl(ImportD);
13048
13049 // Make the module visible.
Douglas Gregorfb912652013-03-20 21:10:35 +000013050 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13051 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013052}
13053
David Chisnall0867d9c2012-02-18 16:12:34 +000013054void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13055 IdentifierInfo* AliasName,
13056 SourceLocation PragmaLoc,
13057 SourceLocation NameLoc,
13058 SourceLocation AliasNameLoc) {
13059 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13060 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000013061 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13062 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000013063
13064 if (PrevDecl)
13065 PrevDecl->addAttr(Attr);
13066 else
13067 (void)ExtnameUndeclaredIdentifiers.insert(
13068 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13069}
13070
Eli Friedman5ed51982009-06-05 02:44:36 +000013071void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13072 SourceLocation PragmaLoc,
13073 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013074 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013075
Eli Friedman5ed51982009-06-05 02:44:36 +000013076 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000013077 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013078 } else {
13079 (void)WeakUndeclaredIdentifiers.insert(
13080 std::pair<IdentifierInfo*,WeakInfo>
13081 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013082 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013083}
13084
13085void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13086 IdentifierInfo* AliasName,
13087 SourceLocation PragmaLoc,
13088 SourceLocation NameLoc,
13089 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013090 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13091 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013092 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013093
Eli Friedman5ed51982009-06-05 02:44:36 +000013094 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013095 if (!PrevDecl->hasAttr<AliasAttr>())
13096 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013097 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013098 } else {
13099 (void)WeakUndeclaredIdentifiers.insert(
13100 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013101 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013102}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013103
13104Decl *Sema::getObjCDeclContext() const {
13105 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13106}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013107
13108AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013109 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013110 // If we are within an Objective-C method, we should consult
13111 // both the availability of the method as well as the
13112 // enclosing class. If the class is (say) deprecated,
13113 // the entire method is considered deprecated from the
13114 // purpose of checking if the current context is deprecated.
13115 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13116 AvailabilityResult R = MD->getAvailability();
13117 if (R != AR_Available)
13118 return R;
13119 D = MD->getClassInterface();
13120 }
13121 // If we are within an Objective-c @implementation, it
13122 // gets the same availability context as the @interface.
13123 else if (const ObjCImplementationDecl *ID =
13124 dyn_cast<ObjCImplementationDecl>(D)) {
13125 D = ID->getClassInterface();
13126 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013127 return D->getAvailability();
13128}